Skip to content

Instantly share code, notes, and snippets.

Created March 20, 2023 10:31
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
What would you like to do?
Assert `isInstanceOf` extensions to improve readablity of JUnit test assertions. I've found this most useful when asserting sealed class result objects as you can asset it's the correct type and then via smart casting continue to assert any specifics of the result, in the sample below I assert the type and then taskId.
import org.assertj.core.api.AbstractObjectAssert
inline fun <reified R> AbstractObjectAssert<*, *>.isNotInstanceOf(): AbstractObjectAssert<*, *>? =
inline fun <reified R> AbstractObjectAssert<*, *>.isInstanceOf(): AbstractObjectAssert<*, *>? =
inline fun <reified R> AbstractObjectAssert<*, *>.isInstanceOf(
crossinline requirements: (R) -> Unit
): AbstractObjectAssert<*, *>? =
isInstanceOfSatisfying( { requirements(it) }
import com.nhaarman.mockitokotlin2.any
import com.nhaarman.mockitokotlin2.never
import com.nhaarman.mockitokotlin2.verify
import com.nhaarman.mockitokotlin2.whenever
import com.myapp.challenge.isInstanceOf
import kotlinx.coroutines.test.runTest
import org.assertj.core.api.AssertionsForInterfaceTypes.assertThat
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
import org.mockito.Mock
import org.mockito.junit.MockitoJUnitRunner
class StartTaskUsecaseTest {
private lateinit var taskRepository: TaskRepository
private lateinit var sut: StartTaskUsecase
fun setUp() {
sut = StartTaskUsecase(taskRepository)
fun `invoke SHOULD create new activity WHEN there is not current Activity`() {
runTest {
val newTaskId = "123"
val task = Task(id = newTaskId)
val result = sut.invoke()
// use of custom isInstanceOf instead of `isInstanceOf(`
assertThat(result).isInstanceOf<Success> {
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment