Created
March 20, 2023 10:31
-
-
Save scottyab/86980f274e6a4a92e974ffee2b307763 to your computer and use it in GitHub Desktop.
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import org.assertj.core.api.AbstractObjectAssert | |
@Suppress("UNCHECKED_CAST") | |
inline fun <reified R> AbstractObjectAssert<*, *>.isNotInstanceOf(): AbstractObjectAssert<*, *>? = | |
isNotInstanceOf(R::class.java) | |
@Suppress("UNCHECKED_CAST") | |
inline fun <reified R> AbstractObjectAssert<*, *>.isInstanceOf(): AbstractObjectAssert<*, *>? = | |
isInstanceOf(R::class.java) | |
@Suppress("UNCHECKED_CAST") | |
inline fun <reified R> AbstractObjectAssert<*, *>.isInstanceOf( | |
crossinline requirements: (R) -> Unit | |
): AbstractObjectAssert<*, *>? = | |
isInstanceOfSatisfying(R::class.java) { requirements(it) } |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | |
@RunWith(MockitoJUnitRunner::class) | |
class StartTaskUsecaseTest { | |
@Mock | |
private lateinit var taskRepository: TaskRepository | |
private lateinit var sut: StartTaskUsecase | |
@Before | |
fun setUp() { | |
sut = StartTaskUsecase(taskRepository) | |
} | |
@Test | |
fun `invoke SHOULD create new activity WHEN there is not current Activity`() { | |
runTest { | |
val newTaskId = "123" | |
val task = Task(id = newTaskId) | |
whenever(taskRepository.newTask()).thenReturn(task) | |
val result = sut.invoke() | |
// use of custom isInstanceOf instead of `isInstanceOf(Success::class.java)` | |
assertThat(result).isInstanceOf<Success> { | |
assertThat(it.taskId).isEqualTo(newTaskId) | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment