Best Mockito-kotlin code snippet using org.mockito.kotlin.Matchers.argThat
CheckoutUseCaseTest.kt
Source:CheckoutUseCaseTest.kt
...16import org.junit.runner.RunWith17import org.mockito.Mock18import org.mockito.internal.matchers.apachecommons.ReflectionEquals19import org.mockito.junit.MockitoJUnitRunner20import org.mockito.kotlin.argThat21import org.mockito.kotlin.verify22import org.mockito.kotlin.verifyNoInteractions23import org.mockito.kotlin.verifyNoMoreInteractions24import org.mockito.kotlin.whenever25@RunWith(MockitoJUnitRunner::class)26class CheckoutUseCaseTest {27 @Mock28 private lateinit var success: CallbackTest<CheckoutResponse>29 @Mock30 private lateinit var failure: CallbackTest<MercadoPagoError>31 @Mock32 private lateinit var tracker: MPTracker33 @Mock34 private lateinit var checkoutRepository: CheckoutRepository35 private lateinit var testContextProvider: TestContextProvider36 private lateinit var checkoutUseCase: CheckoutUseCase37 @Before38 fun setUp() {39 testContextProvider = TestContextProvider()40 checkoutUseCase = CheckoutUseCase(checkoutRepository, tracker, testContextProvider)41 }42 @Test43 fun whenApiReturnsSuccessAndNoCardIdProvidedThenItShouldReturnSuccessWithResponse() {44 val checkoutResponse = CheckoutResponseStub.FULL.get()45 runBlocking {46 whenever(checkoutRepository.checkout()).thenReturn(Response.Success(checkoutResponse))47 }48 checkoutUseCase.execute(49 Unit,50 success::invoke,51 failure::invoke52 )53 verify(success).invoke(argThat { ReflectionEquals(checkoutResponse).matches(this) })54 }55 @Test56 fun whenApiReturnsSuccessAndNoCardIdProvidedThenItShouldCallCheckoutAndConfigureButNotSort() {57 val checkoutResponse = CheckoutResponseStub.FULL.get()58 runBlocking {59 whenever(checkoutRepository.checkout()).thenReturn(Response.Success(checkoutResponse))60 }61 checkoutUseCase.execute(62 Unit,63 success::invoke,64 failure::invoke65 )66 runBlocking {67 verify(checkoutRepository).checkout()68 }69 verify(checkoutRepository).configure(checkoutResponse)70 verifyNoMoreInteractions(checkoutRepository)71 }72 @Test73 fun whenApiReturnsFailureThenItShouldReturnRecoverableMercadoPagoErrorWithApiException() {74 val apiExceptionMsg = "test message"75 val apiException = ApiException().apply { message = apiExceptionMsg }76 runBlocking {77 whenever(checkoutRepository.checkout()).thenReturn(78 Response.Failure(MercadoPagoError(apiException, ApiUtil.RequestOrigin.POST_INIT)))79 }80 checkoutUseCase.execute(81 Unit,82 success::invoke,83 failure::invoke84 )85 runBlocking {86 verify(checkoutRepository).checkout()87 verifyNoMoreInteractions(checkoutRepository)88 }89 verifyNoInteractions(success)90 verify(failure).invoke(argThat { this.apiException.message == apiExceptionMsg && this.isRecoverable })91 }92 @Test(expected = Exception::class)93 fun whenRepositoryThrowsExceptionThenItShouldReturnNoRecoverableMercadoPagoError() {94 val exceptionMsg = "test message"95 val exception = Exception().apply {96 whenever(localizedMessage).thenReturn(exceptionMsg)97 }98 runBlocking {99 whenever(checkoutRepository.checkout()).thenThrow(exception)100 }101 checkoutUseCase.execute(102 Unit,103 success::invoke,104 failure::invoke105 )106 runBlocking {107 verify(checkoutRepository).checkout()108 verifyNoMoreInteractions(checkoutRepository)109 }110 verifyNoInteractions(success)111 verify(failure).invoke(argThat { this.apiException.message == exceptionMsg && !this.isRecoverable })112 }113}...
Matchers.kt
Source:Matchers.kt
...55 * `null` values will never evaluate to `true`.56 *57 * @param predicate An extension function on [T] that returns `true` when a [T] matches the predicate.58 */59inline fun <reified T : Any> argThat(noinline predicate: T.() -> Boolean): T {60 return ArgumentMatchers.argThat { arg: T? -> arg?.predicate() ?: false } ?: createInstance(61 T::class62 )63}64/**65 * Registers a custom ArgumentMatcher. The original Mockito function registers the matcher and returns null,66 * here the required type is returned.67 *68 * @param matcher The ArgumentMatcher on [T] to be registered.69 */70inline fun <reified T : Any> argThat(matcher: ArgumentMatcher<T>): T {71 return ArgumentMatchers.argThat(matcher) ?: createInstance()72}73/**74 * Alias for [argThat].75 *76 * Creates a custom argument matcher.77 * `null` values will never evaluate to `true`.78 *79 * @param predicate An extension function on [T] that returns `true` when a [T] matches the predicate.80 */81inline fun <reified T : Any> argForWhich(noinline predicate: T.() -> Boolean): T {82 return argThat(predicate)83}84/**85 * Creates a custom argument matcher.86 * `null` values will never evaluate to `true`.87 *88 * @param predicate A function that returns `true` when given [T] matches the predicate.89 */90inline fun <reified T : Any> argWhere(noinline predicate: (T) -> Boolean): T {91 return argThat(predicate)92}93/**94 * Argument that implements the given class.95 */96inline fun <reified T : Any> isA(): T {97 return ArgumentMatchers.isA(T::class.java) ?: createInstance()98}99/**100 * `null` argument.101 */102fun <T : Any> isNull(): T? = ArgumentMatchers.isNull()103/**104 * Not `null` argument.105 */...
MockitoKt.kt
Source:MockitoKt.kt
...33 * Wrapper around [Mockito.any] for generic types.34 */35 inline fun <reified T> any() = any(T::class.java)36 /**37 * Wrapper around [Mockito.argThat] that doesn't return null.38 * If used with Kotlin functions that do not accept nullable types it causes a "must not be null" exception.39 *40 * Using the not-null assertion operator (!!) doesn't work because the result of the method call is recorded internally by Mockito.41 * @see Mockito.argThat42 */43 fun <T> argThat(arg: (T) -> Boolean): T = Mockito.argThat(arg)44 /**45 * Convenience wrapper around [Mockito.mock] that allows the type to be inferred.46 */47 inline fun <reified T> mock(): T = Mockito.mock(T::class.java)48 /**49 * Convenience wrapper around [Mockito.mockStatic] that allows the type to be inferred.50 */51 inline fun <reified T> mockStatic(): MockedStatic<T> = Mockito.mockStatic(T::class.java)52 /**53 * Convenience wrapper around [InvocationOnMock.getArgument] that allows the type to be inferred.54 */55 inline fun <reified T> InvocationOnMock.getTypedArgument(i: Int): T = getArgument(i, T::class.java)56 /**57 * Wrapper around [Mockito.eq] that doesn't return null....
LegacyClientTest.kt
Source:LegacyClientTest.kt
...27import org.jetbrains.kotlin.utils.addToStdlib.firstIsInstance28import org.junit.Rule29import org.junit.Test30import org.mockito.ArgumentMatchers31import org.mockito.ArgumentMatchers.argThat32import org.mockito.Mockito.`when`33import org.mockito.Mockito.mock34import org.mockito.Mockito.verify35class LegacyClientTest {36 @get:Rule37 val adbRule = FakeAdbRule()38 @get:Rule39 val projectRule = AndroidProjectRule.inMemory()40 @get:Rule41 val clientFactoryRule = PropertySetterRule(42 { _, parentDisposable -> listOf(LegacyClient(ResourceLookup(projectRule.project), parentDisposable)) },43 InspectorClient.Companion::clientFactory)44 @Test45 fun testReloadAllWindows() {46 val inspector = LayoutInspector(InspectorModel(projectRule.project), projectRule.fixture.projectDisposable)47 val client = inspector.allClients.firstIsInstance<LegacyClient>()48 val loader = mock(LegacyTreeLoader::class.java)49 `when`(loader.getAllWindowIds(ArgumentMatchers.any(), eq(client))).thenReturn(listOf("window1", "window2", "window3"))50 client.treeLoader = loader51 client.reloadAllWindows()52 verify(loader).loadComponentTree(argThat { event: LegacyEvent -> event.windowId == "window1" },53 any(ResourceLookup::class.java), eq(client), eq(projectRule.project))54 verify(loader).loadComponentTree(argThat { event: LegacyEvent -> event.windowId == "window2" },55 any(ResourceLookup::class.java), eq(client), eq(projectRule.project))56 verify(loader).loadComponentTree(argThat { event: LegacyEvent -> event.windowId == "window3" },57 any(ResourceLookup::class.java), eq(client), eq(projectRule.project))58 }59 @Test60 fun testReloadAllWindowsWithNone() {61 val inspector = LayoutInspector(InspectorModel(projectRule.project), projectRule.fixture.projectDisposable)62 val client = inspector.allClients.firstIsInstance<LegacyClient>()63 val loader = mock(LegacyTreeLoader::class.java)64 `when`(loader.getAllWindowIds(ArgumentMatchers.any(), eq(client))).thenReturn(emptyList())65 client.treeLoader = loader66 assertThat(client.reloadAllWindows()).isFalse()67 }68}...
EventSenderTest.kt
Source:EventSenderTest.kt
...8import org.junit.Assert.assertNotEquals9import org.junit.Before10import org.junit.Test11import org.mockito.ArgumentMatchers.any12import org.mockito.ArgumentMatchers.argThat13import org.mockito.Mock14import org.mockito.Mockito.inOrder15import org.mockito.Mockito.never16import org.mockito.Mockito.verify17import org.mockito.MockitoAnnotations18import java.util.concurrent.ThreadPoolExecutor19class EventSenderTest {20 private lateinit var sender: EventSenderImpl21 @Mock private lateinit var client: OkHttpClient22 @Mock private lateinit var executor: ThreadPoolExecutor23 @Before24 fun setup() {25 MockitoAnnotations.initMocks(this)26 sender = EventSenderImpl(client, executor, "app1", "local1", "device1")27 }28 @Test29 fun eventHasCorrectInformation() {30 val event = object : Event() {}31 sender.send(event)32 assertEquals("local1", event.localID)33 assertEquals("device1", event.deviceID)34 }35 @Test36 fun eventWillNotOverwriteTimestamp() {37 val event = object : Event() {}38 event.timestamp = 300L39 sender.send(event)40 assertEquals(300L, event.timestamp)41 event.timestamp = 0L42 sender.send(event)43 assertNotEquals(0L, event.timestamp)44 }45 @Test46 fun sendEventBeforeNeededState() {47 sender.send(UserJoinEvent("con1"))48 sender.send(FabricTerminatedEvent("remote1", "con1"))49 assertEquals(1, sender.authenticatedQueue.size)50 assertEquals(1, sender.sessionQueue.size)51 verify(executor, never()).execute(any())52 }53 @Test54 fun sendEventsInCorrectOrder() {55 whenever(executor.execute(any()))56 .then {57 val runnable = (it.getArgument(0) as EventSendingRunnable)58 val map = when {59 runnable.event is AuthenticationEvent -> mapOf("access_token" to "1234")60 runnable.event is CreateSessionEvent -> mapOf("ucID" to "5678")61 else -> emptyMap()62 }63 runnable.callback.invoke(runnable.event, true, map)64 }65 // send event in reverse order66 sender.send(object : SessionEvent() {})67 sender.send(object : CreateSessionEvent() {})68 sender.send(object : Event(), AuthenticationEvent {69 override val code: String = "code"70 override val clientID: String = "clientID"71 })72 // verify that event sent in correct order73 val order = inOrder(executor)74 order.verify(executor).execute(argThat{ (it as EventSendingRunnable).event is AuthenticationEvent })75 order.verify(executor).execute(argThat{ (it as EventSendingRunnable).event is CreateSessionEvent })76 order.verify(executor).execute(argThat{ (it as EventSendingRunnable).event is SessionEvent })77 }78 @Test79 fun willNotSaveKeepAliveEvent() {80 sender.send(UserAliveEvent())81 assertEquals(0, sender.sessionQueue.size)82 }83}...
MockitoMatchers.kt
Source:MockitoMatchers.kt
...43 private val hamcrestMatcher: Matcher<Array<out T>>44 ) : ArgumentMatcher<Array<out T>>, VarargMatcher {45 companion object {46 inline fun <reified T> varArgThat(hamcrestMatcher: Matcher<Array<out T>>): Array<out T> {47 ArgumentMatchers.argThat(VarArgMatcher(hamcrestMatcher))48 return Array(0) { null as T }49 }50 }51 override fun matches(argument: Array<out T>): Boolean = hamcrestMatcher.matches(argument)52 }53 /**54 * Android's Mockito argument captors are made for Java,55 * so [ArgumentCaptor.capture] always returns nullable classes.56 *57 * To make it work with kotlin's functions, need to explicitly cast58 * the return value to it's non-null version.59 */60 fun <T> capture(argumentCaptor: ArgumentCaptor<T>): T = argumentCaptor.capture()61}...
KMockito.kt
Source:KMockito.kt
...19 *20 * @return a Kotlin-friendly matcher that matches any argument value and will never return21 * a non-null reference22 */23 fun <T> any(dummyInstance: T) = argThat(KAny(dummyInstance))24 /**25 * Kotlin-friendly matcher. This matcher will always return a non-null reference that26 * keeps the Kotlin runtime happy.27 *28 * @param matcher the matcher that will actually perform the desired argument matching29 *30 * @return a Kotlin-friendly matcher that matches any argument value and will never return31 * a non-null reference32 *33 * @see KArgumentMatcher34 */35 fun <T> argThat(matcher: KArgumentMatcher<T>): T {36 return Mockito.argThat(matcher) ?: matcher.dummyInstance()37 }38 /**39 * Mockito.when function for suspended method calls.40 */41 fun <T> suspendedWhen(methodCall: suspend () -> T): OngoingStubbing<T> {42 return Mockito.`when`(runBlocking { methodCall.invoke() })43 }44 /**45 * Mockito.verify function for suspended method calls.46 */47 fun <T> suspendedVerify(mock: T, method: suspend T.() -> Unit) {48 runBlocking { Mockito.verify(mock).method() }49 }50 /**...
AemImportRepositoryTest.kt
Source:AemImportRepositoryTest.kt
...8import org.hamcrest.MatcherAssert.assertThat9import org.hamcrest.Matchers.lessThanOrEqualTo10import org.junit.Assert.assertTrue11import org.junit.Test12import org.mockito.kotlin.argThat13import org.mockito.kotlin.argumentCaptor14import org.mockito.kotlin.eq15import org.mockito.kotlin.inOrder16import org.mockito.kotlin.mock17@OptIn(ExperimentalCoroutinesApi::class)18class AemImportRepositoryTest : AbstractArticleRoomDatabaseTest() {19 private val repo = object : AemImportRepository(db) {}20 @Test21 fun `accessAemImport()`() = runTest {22 val uri = mock<Uri>()23 val start = Date()24 repo.accessAemImport(uri)25 val end = Date()26 inOrder(aemImportDao) {27 verify(aemImportDao).insertOrIgnore(argThat<AemImport> { this.uri == uri })28 argumentCaptor<Date> {29 verify(aemImportDao).updateLastAccessed(eq(uri), capture())30 assertTrue(start == firstValue || start.before(firstValue))31 assertTrue(end == firstValue || end.after(firstValue))32 }33 verifyNoMoreInteractions()34 }35 }36 @Test37 fun `removeOrphanedAemImports()`() = runTest {38 repo.removeOrphanedAemImports()39 val accessedBefore = argumentCaptor<Date>()40 inOrder(aemImportDao, articleRepository) {41 verify(aemImportDao).removeOrphanedAemImports(accessedBefore.capture())...
argThat
Using AI Code Generation
1val list = mock<MutableList<String>>()2whenever(list[0]).then { "First" }3whenever(list[1]).then { "Second" }4whenever(list[2]).then { "Third" }5verify(list).get(argThat { startsWith("F") })6verify(list).get(argThat { endsWith("st") })7verify(list).get(argThat { contains("ir") })8verify(list).get(argThat { matches(".*ir.*".toRegex()) })9verify(list).get(argThat { it == "First" })10verify(list).get(argThat { it != "Second" })11verify(list).get(argThat { it > "Second" })12verify(list).get(argThat { it < "Third" })13verify(list).get(argThat { it >= "First" })14verify(list).get(argThat { it <= "Third" })15verify(list).get(argThat { it != null })16verify(list).get(argThat { it == null })17verify(list).get(argThat { it in 1..10 })18verify(list).get(argThat { it !in 1..10 })
argThat
Using AI Code Generation
1val mockedList = mock<MutableList<String>>()2every { mockedList.add(any()) } just Runs3mockedList.add("one")4mockedList.add("two")5verify(exactly = 2) { mockedList.add(any()) }6every { mockedList.add(argThat { it.startsWith("a") }) } just Runs7mockedList.add("one")8mockedList.add("two")9verify(exactly = 2) { mockedList.add(argThat { it.startsWith("a") }) }10every { mockedList.add(argThat { it.length > 3 }) } just Runs11mockedList.add("one")12mockedList.add("two")13verify(exactly = 2) { mockedList.add(argThat { it.length > 3 }) }14every { mockedList.add(argThat { it.length > 3 }) } just Runs15mockedList.add("one")16mockedList.add("two")17verify(exactly = 2) { mockedList.add(argThat { it.length > 3 }) }18every { mockedList.add(argThat { it.startsWith("a") }) } just Runs19mockedList.add("one")20mockedList.add("two")21verify(exactly = 2) { mockedList.add(argThat { it.startsWith("a") }) }22every { mockedList.add(argThat { it.length > 3 }) } just Runs23mockedList.add("one")24mockedList.add("two")25verify(exactly = 2) { mockedList.add(argThat { it.length > 3 }) }26every { mockedList.add(argThat { it.startsWith("a") }) } just Runs27mockedList.add("one")28mockedList.add("two")29verify(exactly = 2) { mockedList.add(argThat { it.startsWith("a") }) }30every { mockedList.add(argThat { it.length > 3 }) } just Runs31mockedList.add("one")32mockedList.add("two")33verify(exactly = 2) { mockedList.add(argThat { it.length > 3 }) }34every { mockedList.add(argThat { it.startsWith("a
argThat
Using AI Code Generation
1val list = mock<List<String>>()2val arg = argThat { it.size > 1 }3val arg2 = argThat { it.size > 2 }4verify(list).get(arg)5verify(list).get(arg2)6val list = mock<List<String>>()7val arg = argThat(object : ArgumentMatcher<Int>() {8override fun matches(argument: Int?): Boolean = argument!! > 19})10val arg2 = argThat(object : ArgumentMatcher<Int>() {11override fun matches(argument: Int?): Boolean = argument!! > 212})13verify(list).get(arg)14verify(list).get(arg2)15val list = mock<List<String>>()16val arg = argThat { it > 1 }17val arg2 = argThat { it > 2 }18verify(list).get(arg)19verify(list).get(arg2)20val list = mock<List<String>>()21val arg = argThat(object : ArgumentMatcher<Int>() {22override fun matches(argument: Int?): Boolean = argument!! > 123})24val arg2 = argThat(object : ArgumentMatcher<Int>() {25override fun matches(argument: Int?): Boolean = argument!! > 226})27verify(list).get(arg)28verify(list).get(arg2)29val list = mock<List<String>>()30val arg = argThat { it > 1 }31val arg2 = argThat { it > 2 }32verify(list).get(arg)33verify(list).get(arg2)34val list = mock<List<String>>()35val arg = argThat(object : ArgumentMatcher<Int>() {36override fun matches(argument: Int?): Boolean = argument!! > 137})38val arg2 = argThat(object : ArgumentMatcher<Int>() {39override fun matches(argument: Int?): Boolean = argument!! > 240})41verify(list).get(arg)42verify(list).get(arg2)43val list = mock<List<String>>()44val arg = argThat { it > 1 }45val arg2 = argThat { it > 2 }46verify(list).get(arg)47verify(list).get(arg2)
argThat
Using AI Code Generation
1 val mock = mock<SomeInterface>()2 val argumentCaptor = argumentCaptor<String>()3 verify(mock).someMethod(argumentCaptor.capture())4 assertThat(argumentCaptor.value, containsString("some text"))5 import org.mockito.ArgumentMatchers6 import org.mockito.kotlin.argumentCaptor7 import org.mockito.kotlin.verify8 val mock = mock<SomeInterface>()9 val argumentCaptor = argumentCaptor<String>()10 verify(mock).someMethod(argumentCaptor.capture())11 assertThat(argumentCaptor.value, ArgumentMatchers.containsString("some text"))
argThat
Using AI Code Generation
1import org.junit.Assert.assertEquals2import org.junit.Test3import org.junit.runner.RunWith4import org.mockito.BDDMockito.given5import org.mockito.Mock6import org.mockito.junit.MockitoJUnitRunner7@RunWith(MockitoJUnitRunner::class)8class MockitoKotlinDSLUnitTest {9fun given_when_then() {10given(mock.someMethod("test")).willReturn("test")11assertEquals("test", mock.someMethod("test"))12}13}
argThat
Using AI Code Generation
1fun test() {2given(mock.someMethod(argThat { it == 10 })) .willReturn("some value")3}4fun test() {5given(mock.someMethod(argThat { it == 10 })) .willReturn("some value")6}710. Invalid: argument matcher (argument of type java.lang.Integer) is created with constructor Integer(Integer) but should be created with constructor Integer(int) (
argThat
Using AI Code Generation
1val expected = Person("John", 30)2val actual = Person("John", 30)3mockedPersonService.savePerson(expected)4verify(mockedPersonService).savePerson(argThat { name == actual.name && age == actual.age })5val expected = Person("John", 30)6mockedPersonService.savePerson(expected)7verify(mockedPersonService).savePerson(any())8val expected = Person("John", 30)9mockedPersonService.savePerson(expected)10verify(mockedPersonService).savePerson(any())11val expected = Person("John", 30)12mockedPersonService.savePerson(expected)13verify(mockedPersonService).savePerson(any())14val expected = Person("John", 30)15mockedPersonService.savePerson(expected)16verify(mockedPersonService).savePerson(any())17val expected = Person("John", 30)18mockedPersonService.savePerson(expected)19verify(mockedPersonService).savePerson(any())20val expected = Person("John", 30)21mockedPersonService.savePerson(expected)22verify(mockedPersonService).savePerson(any())23val expected = Person("John", 30)24mockedPersonService.savePerson(expected)25verify(mockedPersonService).savePerson(any())26val expected = Person("John", 30)27mockedPersonService.savePerson(expected)28verify(mockedPersonService).savePerson(any())29val expected = Person("John", 30)30mockedPersonService.savePerson(expected)31verify(mockedPersonService).savePerson(any())
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!