How to use isNull method of org.mockito.kotlin.Matchers class

Best Mockito-kotlin code snippet using org.mockito.kotlin.Matchers.isNull

RandomCasesTest.kt

Source:RandomCasesTest.kt Github

copy

Full Screen

2import com.nhaarman.mockito_kotlin.any3import com.nhaarman.mockito_kotlin.doAnswer4import com.nhaarman.mockito_kotlin.doCallRealMethod5import com.nhaarman.mockito_kotlin.doNothing6import com.nhaarman.mockito_kotlin.isNull7import com.nhaarman.mockito_kotlin.verify8import com.nhaarman.mockito_kotlin.withSettings9import org.junit.Assert10import org.junit.Before11import org.junit.Test12import org.mockito.ArgumentCaptor13import org.mockito.ArgumentMatchers14import org.mockito.Mock15import org.mockito.Mockito16import org.mockito.Mockito.`when`17import org.mockito.Mockito.anyInt18import org.mockito.Mockito.anyLong19import org.mockito.Mockito.doThrow20import org.mockito.Mockito.mock21import org.mockito.Mockito.times22import org.mockito.MockitoAnnotations23import org.mockito.invocation.InvocationOnMock24import org.mockito.stubbing.Answer25import java.lang.Exception26import kotlin.random.Random27class RandomCasesTest {28 @Mock29 private lateinit var mockList: MutableList<Long>30 @Before31 fun before() {32 MockitoAnnotations.initMocks(this)33 }34 @Test35 fun `configure simple return behavior for mock`() {36 // Arrange37 `when`(mockList.add(any())).thenReturn(false)38 // Act39 val added = mockList.add(Random.nextLong())40 // Assert41 Assert.assertEquals(added, false)42 }43 @Test44 fun `configure return behavior for mock in an alternative way`() {45 // Arrange46 Mockito.doReturn(false).`when`(mockList).add(ArgumentMatchers.anyLong())47 // Act48 val added = mockList.add(Random.nextLong())49 // Assert50 Assert.assertEquals(added, false)51 }52 @Test(expected = IllegalStateException::class)53 fun `configure mock to throw an exception on a method call`() {54 // Arrange55 `when`(mockList.add(any())).thenThrow(IllegalStateException::class.java)56 // Act57 mockList.add(Random.nextLong())58 }59 @Test(expected = NullPointerException::class)60 fun `configure the behavior of a method with void return type – to throw an exception`() {61 // Arrange62 doThrow(NullPointerException::class.java).`when`(mockList).clear()63 // Act64 mockList.clear()65 }66 @Test67 fun `configure the behavior of a method with void return type`() {68 // Arrange69 doNothing().`when`(mockList).add(anyInt(), anyLong())70 // Act71 mockList.add(0, 1L)72 // Assert73 verify(mockList, times(1)).add(0, 1L)74 }75 /**76 * doNothing() is Mockito's default behavior for void methods!77 */78 @Test79 fun `configure the behavior of a method with void return type - default behavior`() {80 // Act81 mockList.add(0, 1L)82 // Assert83 verify(mockList, times(1)).add(0, 1L)84 }85 @Test(expected = Exception::class)86 fun `configure the behavior of a method with void return type - throw default exception`() {87 // Arrange88 val myNullableMockList = mock(MyList::class.java)89 doThrow().`when`(myNullableMockList).add(anyInt(), isNull())90 // Act91 myNullableMockList.add(0, null)92 }93 /**94 * One reason to override the default behavior with doNothing() is to capture arguments.95 */96 @Test97 fun `configure the behavior of a method with void return type - capturing`() {98 // Arrange99 val valueCapture = ArgumentCaptor.forClass(Long::class.java)100 doNothing().`when`(mockList).add(anyInt(), valueCapture.capture())101 // Act102 val entry = Random.nextLong()103 mockList.add(0, entry)...

Full Screen

Full Screen

GoogleOauth2ControllerTest.kt

Source:GoogleOauth2ControllerTest.kt Github

copy

Full Screen

...9import org.junit.jupiter.api.Test10import org.junit.jupiter.api.extension.ExtendWith11import org.mockito.kotlin.any12import org.mockito.kotlin.eq13import org.mockito.kotlin.isNull14import org.mockito.kotlin.whenever15import org.springframework.beans.factory.annotation.Autowired16import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc17import org.springframework.boot.test.context.SpringBootTest18import org.springframework.boot.test.mock.mockito.MockBean19import org.springframework.test.context.junit.jupiter.SpringExtension20import org.springframework.test.web.servlet.MockMvc21import org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get22import org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post23import org.springframework.test.web.servlet.result.MockMvcResultMatchers.content24import org.springframework.test.web.servlet.result.MockMvcResultMatchers.redirectedUrl25import org.springframework.test.web.servlet.result.MockMvcResultMatchers.status26@ExtendWith(SpringExtension::class)27@SpringBootTest(28 classes = [29 GoogleOauth2Controller::class,30 WebMvcConfiguration::class,31 ApiTestConfiguration::class32 ]33)34@AutoConfigureMockMvc35class GoogleOauth2ControllerTest(36 @Autowired val mockMvc: MockMvc37) {38 @MockBean39 lateinit var googleOauth2ApplicationService: GoogleOauth2ApplicationService40 private val userId = UserId(1)41 private val jwt = "eyJraWQiOiJrZXktaWQiLCJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9." +42 "eyJzdWIiOiJiYWx5c0B5b3Vyc2FtYS5jb20iLCJ1c2VyX2lkIjoiNjViOTc3ZWEtODk4MC00YjFhLWE2ZWUtZjhmY2MzZjFmYzI0Iiwi" +43 "ZXhwIjoxNjIyNTA1NjYwLCJpYXQiOjE2MjI1MDU2MDAsImp0aSI6IjNlNWE3NTY3LWZmYmQtNDcxYi1iYTI2LTU2YjMwOTgwMWZlZSJ9." +44 "hcAQ6f8kaeB43nzFibGYZE8QWHyz9OIdFg9zHSbe9Vk"45 private val mobileUserAgent = "" +46 "Mozilla/5.0 (iPhone; CPU iPhone OS 10_3 like Mac OS X) " +47 "AppleWebKit/602.1.50 (KHTML, like Gecko) CriOS/56.0.2924.75 " +48 "Mobile/14E5239e Safari/602.1"49 @Test50 fun `google authorize returns the authorization url`() {51 val redirectUri = "https://accounts.google.com/o/oauth2/auth?access_type=offline"52 whenever(googleOauth2ApplicationService.generateAuthorizationUrl(any()))53 .thenReturn(GoogleOauth2Redirect(redirectUri))54 val expectedJson = """55 {56 "authorizationUrl": "${redirectUri}"57 }58 """59 mockMvc.perform(post("/api/auth/google-authorize"))60 .andExpect(status().isOk)61 .andExpect(62 content().json(expectedJson, true)63 )64 }65 @Test66 fun `google oauth2 callback success for mobile`() {67 val code = "google-success-code"68 val accessToken = "access-jwt"69 val refreshToken = "refresh-jwt"70 whenever((googleOauth2ApplicationService.processOauth2Callback(any(), eq(code), isNull(), isNull())))71 .thenReturn(GoogleSignSuccessDTO(accessToken, refreshToken))72 mockMvc.perform(73 get("/api/auth/google-oauth2")74 .queryParam("code", code)75 .header("User-Agent", mobileUserAgent)76 )77 .andExpect(status().isFound)78 .andExpect(79 redirectedUrl(80 "meetsama://auth/success" +81 "?accessToken=${accessToken}" +82 "&refreshToken=${refreshToken}"83 )84 )85 }86 @Test87 fun `google oauth2 callback success for desktop`() {88 val code = "google-success-code"89 val accessToken = "access-jwt"90 val refreshToken = "refresh-jwt"91 whenever((googleOauth2ApplicationService.processOauth2Callback(any(), eq(code), isNull(), isNull())))92 .thenReturn(GoogleSignSuccessDTO(accessToken, refreshToken))93 mockMvc.perform(get("/api/auth/google-oauth2").queryParam("code", code))94 .andExpect(status().isFound)95 .andExpect(96 redirectedUrl(97 "meetsama://auth/success" +98 "?accessToken=${accessToken}" +99 "&refreshToken=${refreshToken}"100 )101 )102 }103 @Test104 fun `google oauth2 callback error for mobile`() {105 val code = "google-error-code"106 val error = "error-message"107 whenever((googleOauth2ApplicationService.processOauth2Callback(any(), isNull(), eq(code), isNull())))108 .thenReturn(GoogleSignErrorDTO(error))109 mockMvc.perform(110 get("/api/auth/google-oauth2")111 .queryParam("error", code)112 .header("User-Agent", mobileUserAgent)113 )114 .andExpect(status().isFound)115 .andExpect(116 redirectedUrl(117 "meetsama://auth/error?reason=${error}"118 )119 )120 }121 @Test122 fun `google oauth2 callback error for desktop`() {123 val code = "google-error-code"124 val error = "error_message"125 whenever((googleOauth2ApplicationService.processOauth2Callback(any(), isNull(), eq(code), isNull())))126 .thenReturn(GoogleSignErrorDTO(error))127 mockMvc.perform(get("/api/auth/google-oauth2").queryParam("error", code))128 .andExpect(status().isFound)129 .andExpect(130 redirectedUrl(131 "meetsama://auth/error?reason=${error}"132 )133 )134 }135}...

Full Screen

Full Screen

CustomStudyDialogTest.kt

Source:CustomStudyDialogTest.kt Github

copy

Full Screen

1/*2 Copyright (c) 2020 David Allison <davidallisongithub@gmail.com>3 This program is free software; you can redistribute it and/or modify it under4 the terms of the GNU General Public License as published by the Free Software5 Foundation; either version 3 of the License, or (at your option) any later6 version.7 This program is distributed in the hope that it will be useful, but WITHOUT ANY8 WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A9 PARTICULAR PURPOSE. See the GNU General Public License for more details.10 You should have received a copy of the GNU General Public License along with11 this program. If not, see <http://www.gnu.org/licenses/>.12 */13package com.ichi2.anki.dialogs14import androidx.fragment.app.testing.FragmentScenario15import androidx.lifecycle.Lifecycle16import androidx.test.ext.junit.runners.AndroidJUnit417import com.afollestad.materialdialogs.DialogAction18import com.afollestad.materialdialogs.MaterialDialog19import com.ichi2.anki.R20import com.ichi2.anki.RobolectricTest21import com.ichi2.anki.dialogs.customstudy.CustomStudyDialog22import com.ichi2.anki.dialogs.customstudy.CustomStudyDialog.CustomStudyListener23import com.ichi2.anki.dialogs.customstudy.CustomStudyDialogFactory24import com.ichi2.libanki.Collection25import com.ichi2.libanki.sched.AbstractSched26import com.ichi2.testutils.JsonUtils.toOrderedString27import com.ichi2.testutils.ParametersUtils28import com.ichi2.utils.KotlinCleanup29import org.hamcrest.CoreMatchers.notNullValue30import org.hamcrest.MatcherAssert31import org.hamcrest.Matchers32import org.hamcrest.core.IsNull33import org.junit.After34import org.junit.Test35import org.junit.runner.RunWith36import org.mockito.Mockito37import org.mockito.kotlin.mock38import org.mockito.kotlin.whenever39import org.robolectric.annotation.Config40@RunWith(AndroidJUnit4::class)41class CustomStudyDialogTest : RobolectricTest() {42 private var mMockListener: CustomStudyListener? = null43 override fun setUp() {44 super.setUp()45 mMockListener = Mockito.mock(CustomStudyListener::class.java)46 }47 @After48 override fun tearDown() {49 super.tearDown()50 Mockito.reset(mMockListener)51 }52 @Test53 fun learnAheadCardsRegressionTest() {54 // #6289 - Regression Test55 val args = CustomStudyDialog(mock(), ParametersUtils.whatever())56 .withArguments(CustomStudyDialog.ContextMenuOption.STUDY_AHEAD, 1)57 .arguments58 val factory = CustomStudyDialogFactory({ this.col }, mMockListener)59 val scenario = FragmentScenario.launch(CustomStudyDialog::class.java, args, factory)60 scenario.moveToState(Lifecycle.State.STARTED)61 scenario.onFragment { f: CustomStudyDialog ->62 val dialog = f.dialog as MaterialDialog?63 MatcherAssert.assertThat(dialog, IsNull.notNullValue())64 dialog!!.getActionButton(DialogAction.POSITIVE).callOnClick()65 }66 val customStudy = col.decks.current()67 MatcherAssert.assertThat("Custom Study should be dynamic", customStudy.isDyn)68 MatcherAssert.assertThat("could not find deck: Custom study session", customStudy, notNullValue())69 customStudy.remove("id")70 customStudy.remove("mod")71 customStudy.remove("name")72 val expected = "{" +73 "\"browserCollapsed\":false," +74 "\"collapsed\":false," +75 "\"delays\":null," +76 "\"desc\":\"\"," +77 "\"dyn\":1," +78 "\"lrnToday\":[0,0]," +79 "\"newToday\":[0,0]," +80 "\"previewDelay\":10," +81 "\"resched\":true," +82 "\"revToday\":[0,0]," +83 "\"separate\":true," +84 "\"terms\":[[\"deck:\\\"Default\\\" prop:due<=1\",99999,6]]," +85 "\"timeToday\":[0,0]," +86 "\"usn\":-1" +87 "}"88 MatcherAssert.assertThat(customStudy.toOrderedString(), Matchers.`is`(expected))89 }90 @Test91 @Config(qualifiers = "en")92 @KotlinCleanup("Use kotlin based Mockito extensions")93 fun increaseNewCardLimitRegressionTest() {94 // #8338 - Regression Test95 val args = CustomStudyDialog(mock(), ParametersUtils.whatever())96 .withArguments(CustomStudyDialog.ContextMenuConfiguration.STANDARD, 1)97 .arguments98 // we are using mock collection for the CustomStudyDialog but still other parts of the code99 // access a real collection, so we must ensure that collection is loaded first100 // so we don't get net/ankiweb/rsdroid/BackendException$BackendDbException$BackendDbLockedException101 ensureCollectionLoadIsSynchronous()102 val mockCollection = Mockito.mock(Collection::class.java, Mockito.RETURNS_DEEP_STUBS)103 val mockSched = Mockito.mock(AbstractSched::class.java)104 whenever(mockCollection.sched).thenReturn(mockSched)105 whenever(mockSched.newCount()).thenReturn(0)106 val factory = CustomStudyDialogFactory({ mockCollection }, mMockListener)107 val scenario = FragmentScenario.launch(CustomStudyDialog::class.java, args, R.style.Theme_AppCompat, factory)108 scenario.moveToState(Lifecycle.State.STARTED)109 scenario.onFragment { f: CustomStudyDialog ->110 val dialog = f.dialog as MaterialDialog?111 MatcherAssert.assertThat(dialog, IsNull.notNullValue())112 MatcherAssert.assertThat(dialog!!.items, Matchers.not(Matchers.hasItem(getResourceString(R.string.custom_study_increase_new_limit))))113 }114 }115}...

Full Screen

Full Screen

Matchers.kt

Source:Matchers.kt Github

copy

Full Screen

...98}99/**100 * `null` argument.101 */102fun <T : Any> isNull(): T? = ArgumentMatchers.isNull()103/**104 * Not `null` argument.105 */106fun <T : Any> isNotNull(): T? {107 return ArgumentMatchers.isNotNull()108}109/**110 * Not `null` argument.111 */112fun <T : Any> notNull(): T? {113 return ArgumentMatchers.notNull()114}115/**116 * Object argument that is reflection-equal to the given value with support for excluding...

Full Screen

Full Screen

NomisBatchServiceTest.kt

Source:NomisBatchServiceTest.kt Github

copy

Full Screen

...5import org.mockito.ArgumentMatchers.any6import org.mockito.ArgumentMatchers.anyString7import org.mockito.ArgumentMatchers.eq8import org.mockito.ArgumentMatchers.isA9import org.mockito.ArgumentMatchers.isNull10import org.mockito.Mockito.never11import org.mockito.Mockito.times12import org.mockito.Mockito.verify13import org.mockito.kotlin.whenever14import org.springframework.beans.factory.annotation.Autowired15import org.springframework.boot.test.mock.mockito.MockBean16import org.springframework.test.context.ContextConfiguration17import org.springframework.test.context.junit.jupiter.SpringExtension18import uk.gov.justice.digital.hmpps.keyworker.config.RetryConfiguration19import uk.gov.justice.digital.hmpps.keyworker.dto.CaseloadUpdate20import uk.gov.justice.digital.hmpps.keyworker.dto.Prison21@ExtendWith(SpringExtension::class)22@ContextConfiguration(classes = [NomisBatchService::class, RetryConfiguration::class])23class NomisBatchServiceTest {24 @Autowired25 private lateinit var batchService: NomisBatchService26 @MockBean27 private lateinit var nomisService: NomisService28 @MockBean29 private lateinit var telemetryClient: TelemetryClient30 @Test31 fun enableNomis_makesPrisonApiCalls() {32 val prisons = listOf(MDI, LEI, LPI)33 whenever(nomisService.allPrisons).thenReturn(prisons)34 val MDIResponse = CaseloadUpdate.builder().caseload(MDI.prisonId).numUsersEnabled(2).build()35 whenever(nomisService.enableNewNomisForCaseload(eq(MDI.prisonId))).thenReturn(MDIResponse)36 val LEIResponse = CaseloadUpdate.builder().caseload(LEI.prisonId).numUsersEnabled(0).build()37 whenever(nomisService.enableNewNomisForCaseload(eq(LEI.prisonId))).thenReturn(LEIResponse)38 val LPIResponse = CaseloadUpdate.builder().caseload(LPI.prisonId).numUsersEnabled(14).build()39 whenever(nomisService.enableNewNomisForCaseload(eq(LPI.prisonId))).thenReturn(LPIResponse)40 batchService.enableNomis()41 verify(nomisService).allPrisons42 verify(nomisService).enableNewNomisForCaseload(eq(MDI.prisonId))43 verify(nomisService).enableNewNomisForCaseload(eq(LEI.prisonId))44 verify(nomisService).enableNewNomisForCaseload(eq(LPI.prisonId))45 verify(telemetryClient, times(3)).trackEvent(46 eq("ApiUsersEnabled"),47 isA(48 Map::class.java49 ) as MutableMap<String, String>?,50 isNull()51 )52 }53 @Test54 fun testEnabledNewNomisCamelRoute_NoOpOnGetAllPrisonsError() {55 whenever(nomisService.allPrisons).thenThrow(RuntimeException("Error"))56 batchService.enableNomis()57 verify(nomisService).allPrisons58 verify(nomisService, never()).enableNewNomisForCaseload(anyString())59 verify(telemetryClient, times(0)).trackEvent(60 anyString(),61 any(62 Map::class.java63 ) as MutableMap<String, String>?,64 isNull()65 )66 }67 @Test68 fun testEnabledNewNomisCamelRoute_RetriesOnEnablePrisonsError() {69 val prisons = listOf(MDI)70 whenever(nomisService.allPrisons).thenReturn(prisons)71 val MDIResponse = CaseloadUpdate.builder().caseload(MDI.prisonId).numUsersEnabled(2).build()72 whenever(nomisService.enableNewNomisForCaseload(eq(MDI.prisonId)))73 .thenThrow(RuntimeException("Error"))74 .thenReturn(MDIResponse)75 batchService.enableNomis()76 verify(nomisService).allPrisons77 verify(nomisService, times(2)).enableNewNomisForCaseload(eq(MDI.prisonId))78 verify(telemetryClient, times(1)).trackEvent(79 eq("ApiUsersEnabled"),80 any(81 Map::class.java82 ) as MutableMap<String, String>?,83 isNull()84 )85 }86 companion object {87 private val MDI = Prison.builder().prisonId("MDI").build()88 private val LEI = Prison.builder().prisonId("LEI").build()89 private val LPI = Prison.builder().prisonId("LPI").build()90 }91}...

Full Screen

Full Screen

AuthenticateDeviceUseCaseTests.kt

Source:AuthenticateDeviceUseCaseTests.kt Github

copy

Full Screen

...15import org.mockito.Mockito16import org.mockito.Spy17import org.mockito.junit.MockitoJUnitRunner18import org.mockito.kotlin.any19import org.mockito.kotlin.isNull20import org.mockito.kotlin.verify21import org.mockito.kotlin.whenever22import org.mockito.kotlin.eq23import org.mockito.kotlin.argumentCaptor24@RunWith(MockitoJUnitRunner::class)25class AuthenticateDeviceUseCaseTests {26 @Mock27 lateinit var clientMock: OneginiClient28 @Mock29 lateinit var oneginiDeviceAuthenticationErrorMock: OneginiDeviceAuthenticationError30 @Mock31 lateinit var deviceClientMock: DeviceClient32 @Mock33 lateinit var callMock: MethodCall34 @Spy35 lateinit var resultSpy: MethodChannel.Result36 @Before37 fun attach() {38 whenever(clientMock.deviceClient).thenReturn(deviceClientMock)39 }40 @Test41 fun `should return error when sdk returned authentication error`() {42 whenever(callMock.argument<ArrayList<String>>("scope")).thenReturn(null)43 whenever(oneginiDeviceAuthenticationErrorMock.errorType).thenReturn(OneginiDeviceAuthenticationError.GENERAL_ERROR)44 whenever(oneginiDeviceAuthenticationErrorMock.message).thenReturn("General error")45 whenever(deviceClientMock.authenticateDevice(isNull(), any())).thenAnswer {46 it.getArgument<OneginiDeviceAuthenticationHandler>(1).onError(oneginiDeviceAuthenticationErrorMock)47 }48 AuthenticateDeviceUseCase(clientMock)(callMock, resultSpy)49 verify(resultSpy).error(oneginiDeviceAuthenticationErrorMock.errorType.toString(), oneginiDeviceAuthenticationErrorMock.message, null)50 }51 @Test52 fun `should return success when SDK returned authentication success`() {53 whenever(callMock.argument<ArrayList<String>>("scope")).thenReturn(arrayListOf("test"))54 whenever(deviceClientMock.authenticateDevice(eq(arrayOf("test")), any())).thenAnswer {55 it.getArgument<OneginiDeviceAuthenticationHandler>(1).onSuccess()56 }57 AuthenticateDeviceUseCase(clientMock)(callMock, resultSpy)58 verify(resultSpy).success(true)59 }...

Full Screen

Full Screen

FormViewModelTest.kt

Source:FormViewModelTest.kt Github

copy

Full Screen

1package io.github.gianpamx.android.architecture.form2import android.arch.core.executor.testing.InstantTaskExecutorRule3import com.nhaarman.mockito_kotlin.any4import com.nhaarman.mockito_kotlin.argumentCaptor5import com.nhaarman.mockito_kotlin.isNull6import com.nhaarman.mockito_kotlin.verify7import io.github.gianpamx.android.architecture.entity.Form8import io.github.gianpamx.android.architecture.providers.DateTimeProvider9import io.github.gianpamx.android.architecture.providers.VersionProvider10import io.github.gianpamx.android.architecture.usecase.GetFormUseCase11import io.github.gianpamx.android.architecture.usecase.SaveFormUseCase12import org.junit.Assert.*13import org.junit.Before14import org.junit.Rule15import org.junit.Test16import org.junit.runner.RunWith17import org.mockito.ArgumentMatchers.anyString18import org.mockito.Mock19import org.mockito.junit.MockitoJUnitRunner20import java.util.*21private val FIRST_DATE = Date()22private val SECOND_DATE = Date(FIRST_DATE.time + 1000)23private const val ANY_NAME = "ANY_NAME"24private const val ANY_PHONE = "ANY_PHONE"25@RunWith(MockitoJUnitRunner::class)26class FormViewModelTest {27 @Rule28 @JvmField29 val instantExecutor = InstantTaskExecutorRule()30 @Mock31 lateinit var dateTimeProvider: DateTimeProvider32 @Mock33 lateinit var saveFormUseCase: SaveFormUseCase34 @Mock35 lateinit var getFormUseCase: GetFormUseCase36 @Mock37 lateinit var versionProvider: VersionProvider38 lateinit var formViewModel: FormViewModel39 @Before40 fun setUp() {41 formViewModel = FormViewModel(dateTimeProvider, saveFormUseCase, getFormUseCase, versionProvider)42 }43 @Test44 fun ticker() {45 val captor = argumentCaptor<DateTimeProvider.Listener>()46 verify(dateTimeProvider).start(captor.capture())47 captor.firstValue.onTick(FIRST_DATE)48 assertEquals(FIRST_DATE, formViewModel.dateTime.value);49 captor.firstValue.onTick(SECOND_DATE)50 assertEquals(SECOND_DATE, formViewModel.dateTime.value);51 }52 @Test53 fun sendFailure() {54 val captor = argumentCaptor<(Throwable) -> Unit>()55 formViewModel.send("ANY_STRING", "ANY_STRING")56 verify(saveFormUseCase).execute(anyString(), anyString(), any(), captor.capture())57 captor.firstValue.invoke(Exception())58 assertTrue(formViewModel.error.value is Exception)59 }60 @Test61 fun sendSuccessfully() {62 val captor = argumentCaptor<() -> Unit>()63 formViewModel.send(ANY_NAME, ANY_PHONE)64 verify(saveFormUseCase).execute(anyString(), anyString(), captor.capture(), any())65 captor.firstValue.invoke()66 assertTrue(formViewModel.isFormSaved.value!!)67 }68 @Test69 fun existingFormData() {70 val captor = argumentCaptor<(Form) -> Unit>()71 verify(getFormUseCase).execute(captor.capture(), isNull())72 captor.firstValue.invoke(Form(ANY_NAME, ANY_PHONE))73 assertTrue(formViewModel.isFormSaved.value!!)74 }75 @Test76 fun formNotSaved() {77 verify(getFormUseCase).execute(any(), isNull())78 assertFalse(formViewModel.isFormSaved.value!!)79 }80}...

Full Screen

Full Screen

MatchersExtensions.kt

Source:MatchersExtensions.kt Github

copy

Full Screen

...40inline fun <reified T : Any> refEq(value: T, vararg excludeFields: String): T =41 ArgumentMatchers.refEq(value, *excludeFields).toNotNull()42inline fun <reified T : Any> same(value: T): T =43 ArgumentMatchers.same(value).toNotNull()44inline fun <reified T : Any> isNull(): T =45 ArgumentMatchers.isNull<T>().toNotNull()46inline fun <reified T : Any> notNull(): T =47 ArgumentMatchers.notNull<T>().toNotNull()48fun contains(substring: String): String =49 ArgumentMatchers.contains(substring).toNotNull()50fun matches(regex: String): String =51 ArgumentMatchers.matches(regex).toNotNull()52fun endsWith(suffix: String): String =53 ArgumentMatchers.endsWith(suffix).toNotNull()54fun startsWith(prefix: String): String =55 ArgumentMatchers.startsWith(prefix).toNotNull()56inline fun <reified T : Any> argThat(matcher: ArgumentMatcher<T>): T =57 ArgumentMatchers.argThat(matcher).toNotNull()...

Full Screen

Full Screen

isNull

Using AI Code Generation

copy

Full Screen

1val mockedList = mock<MutableList<String>>()2whenever(mockedList[0]).thenReturn("first")3whenever(mockedList[1]).thenReturn("second")4whenever(mockedList[2]).thenReturn("third")5whenever(mockedList[3]).thenReturn("fourth")6whenever(mockedList[4]).thenReturn("fifth")7whenever(mockedList[5]).thenReturn("sixth")8whenever(mockedList[6]).thenReturn("seventh")9whenever(mockedList[7]).thenReturn("eighth")10whenever(mockedList[8]).thenReturn("ninth")11whenever(mockedList[9]).thenReturn("tenth")12whenever(mockedList[10]).thenReturn("eleventh")13whenever(mockedList[11]).thenReturn("twelfth")14whenever(mockedList[12]).thenReturn("thirteenth")15whenever(mockedList[13]).thenReturn("fourteenth")16whenever(mockedList[14]).thenReturn("fifteenth")17whenever(mockedList[15]).thenReturn("sixteenth")18whenever(mockedList[16]).thenReturn("seventeenth")19whenever(mockedList[17]).thenReturn("eighteenth")20whenever(mockedList[18]).thenReturn("nineteenth")21whenever(mockedList[19]).thenReturn("twentieth")22whenever(mockedList[20]).thenReturn("twenty first")23whenever(mockedList[21]).thenReturn("twenty second")24whenever(mockedList[22]).thenReturn("twenty third")25whenever(mockedList[23]).thenReturn("twenty fourth")26whenever(mockedList[24]).thenReturn("twenty fifth")27whenever(mockedList[25]).thenReturn("twenty sixth")28whenever(mockedList[26]).thenReturn("twenty seventh")29whenever(mockedList[27]).thenReturn("twenty eighth")30whenever(mockedList[28]).thenReturn("twenty ninth")31whenever(mockedList[29]).thenReturn("thirtieth")32whenever(mockedList[30]).thenReturn("thirty first")33whenever(mockedList[31]).thenReturn("thirty second")34whenever(mockedList[32]).thenReturn("thirty third")35whenever(mockedList[33]).thenReturn("thirty fourth")36whenever(mockedList[34]).thenReturn("thirty fifth")37whenever(mockedList[35]).thenReturn("thirty sixth")38whenever(mockedList[36]).thenReturn("thirty seventh")39whenever(mockedList[37]).thenReturn("thirty eighth")40whenever(mockedList[38]).thenReturn("thirty ninth")

Full Screen

Full Screen

isNull

Using AI Code Generation

copy

Full Screen

1val mockedList = mock<MutableList<String>>()2whenever(mockedList[0]).thenReturn("first")3println(mockedList[0])4verify(mockedList)[0]5whenever(mockedList.contains(argThat { it.startsWith("foo") })).thenReturn(true)6whenever(mockedList.contains(nullable())).thenReturn(true)7whenever(mockedList.contains(isNull())).thenReturn(true)8doThrow(NullPointerException::class.java).whenever(mockedList).clear()9mockedList.clear()10val mockedList = mock<MutableList<String>>()11mockedList.add("one")12mockedList.clear()13verify(mockedList).add("one")14verify(mockedList).clear()15val mockedList = mock<MutableList<String>>()16mockedList.add("one")17val argument = argumentCaptor<String>()18verify(mockedList).add(argument.capture())19println(argument.firstValue)20val mockedList = mock<MutableList<String>>()21mockedList.add("one")22mockedList.add("two")23val argument = argumentCaptor<String>()24verify(mockedList, times(2)).add(argument.capture())25println(argument.allValues)26val mockedList = mock<MutableList<String>>()27mockedList.add("one")28mockedList.add("two")29val argument = argumentCaptor<String>()30verify(mockedList, atLeastOnce()).add(argument.capture())31println(argument.allValues)32val mockedList = mock<MutableList<String>>()33mockedList.add("one")34mockedList.add("two")35val argument = argumentCaptor<String>()36verify(mockedList, atLeast(2)).add(argument.capture())37println(argument.allValues)38val mockedList = mock<MutableList<String>>()39mockedList.add("one")

Full Screen

Full Screen

isNull

Using AI Code Generation

copy

Full Screen

1 val mock: MyInterface = mock()2 whenever(mock.myMethod(anyOrNull())).thenReturn("Hello")3 assertEquals("Hello", mock.myMethod(null))4 assertEquals("Hello", mock.myMethod("World"))5 val mock: MyInterface = mock()6 whenever(mock.myMethod(isNull())).thenReturn("Hello")7 assertEquals("Hello", mock.myMethod(null))8 assertEquals("Hello", mock.myMethod("World"))9}10@Suppress("unused")11interface MyInterface {12 fun myMethod(param: String?): String13}

Full Screen

Full Screen

isNull

Using AI Code Generation

copy

Full Screen

1val mockedList = mock<MutableList<String>>()2mockedList.add("one")3verify(mockedList).add("one")4verify(mockedList).add(isNull())5verify(mockedList).add(isA<String>())6verify(mockedList).add(argThat { it == "one" })7verify(mockedList).add(check { it == "one" })8verify(mockedList).add(eq("one"))9verify(mockedList).add(any())10verify(mockedList).add(anyOrNull())11verify(mockedList).add(anyVararg())12verify(mockedList).add(anyVarargOrNull())13verify(mockedList).add(anyVararg())14verify(mockedList).add(anyVarargOrNull())15verify(mockedList).add(anyVararg())16verify(mockedList).add(anyVarargOrNull())17verify(mockedList).add(anyVararg())

Full Screen

Full Screen

Automation Testing Tutorials

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.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run Mockito-kotlin automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful