Best Mockito-kotlin code snippet using test.SpyTest
WindowCallbackWrapperTest.kt
Source:WindowCallbackWrapperTest.kt
1/*2 * Unless explicitly stated otherwise all files in this repository are licensed under the Apache License Version 2.0.3 * This product includes software developed at Datadog (https://www.datadoghq.com/).4 * Copyright 2016-Present Datadog, Inc.5 */6package com.datadog.android.rum.internal.instrumentation.gestures7import android.app.Application8import android.content.res.Resources9import android.view.KeyEvent10import android.view.MenuItem11import android.view.MotionEvent12import android.view.Window13import com.datadog.android.core.internal.CoreFeature14import com.datadog.android.rum.GlobalRum15import com.datadog.android.rum.NoOpRumMonitor16import com.datadog.android.rum.RumActionType17import com.datadog.android.rum.RumAttributes18import com.datadog.android.rum.RumMonitor19import com.datadog.android.utils.forge.Configurator20import com.nhaarman.mockitokotlin2.any21import com.nhaarman.mockitokotlin2.argThat22import com.nhaarman.mockitokotlin2.doReturn23import com.nhaarman.mockitokotlin2.eq24import com.nhaarman.mockitokotlin2.inOrder25import com.nhaarman.mockitokotlin2.mock26import com.nhaarman.mockitokotlin2.spy27import com.nhaarman.mockitokotlin2.verify28import com.nhaarman.mockitokotlin2.verifyZeroInteractions29import com.nhaarman.mockitokotlin2.whenever30import fr.xgouchet.elmyr.Forge31import fr.xgouchet.elmyr.junit5.ForgeConfiguration32import fr.xgouchet.elmyr.junit5.ForgeExtension33import java.lang.ref.WeakReference34import org.assertj.core.api.Assertions.assertThat35import org.junit.jupiter.api.AfterEach36import org.junit.jupiter.api.BeforeEach37import org.junit.jupiter.api.Test38import org.junit.jupiter.api.extension.ExtendWith39import org.junit.jupiter.api.extension.Extensions40import org.mockito.Mock41import org.mockito.junit.jupiter.MockitoExtension42import org.mockito.junit.jupiter.MockitoSettings43import org.mockito.quality.Strictness44@Extensions(45 ExtendWith(46 MockitoExtension::class,47 ForgeExtension::class48 )49)50@ForgeConfiguration(Configurator::class)51@MockitoSettings(strictness = Strictness.LENIENT)52internal class WindowCallbackWrapperTest {53 lateinit var testedWrapper: WindowCallbackWrapper54 @Mock55 lateinit var mockCallback: Window.Callback56 @Mock57 lateinit var mockGestureDetector: GesturesDetectorWrapper58 @Mock59 lateinit var mockAppContext: Application60 @Mock61 lateinit var mockResources: Resources62 @Mock63 lateinit var mockRumMonitor: RumMonitor64 @BeforeEach65 fun `set up`() {66 testedWrapper = WindowCallbackWrapper(67 mockCallback,68 mockGestureDetector69 )70 whenever(mockAppContext.resources).thenReturn(mockResources)71 CoreFeature.contextRef = WeakReference(mockAppContext)72 GlobalRum.registerIfAbsent(mockRumMonitor)73 }74 @AfterEach75 fun `tear down`() {76 CoreFeature.contextRef = WeakReference(null)77 GlobalRum.monitor = NoOpRumMonitor()78 GlobalRum.isRegistered.set(false)79 }80 @Test81 fun `dispatchTouchEvent will delegate to wrapper`(forge: Forge) {82 // Given83 val motionEvent: MotionEvent = mock()84 val spyTest = spy(testedWrapper)85 val aBoolean = forge.aBool()86 whenever(mockCallback.dispatchTouchEvent(motionEvent)).thenReturn(aBoolean)87 doReturn(motionEvent).`when`(spyTest).copyEvent(motionEvent)88 // When89 val returnedValue = spyTest.dispatchTouchEvent(motionEvent)90 // Then91 assertThat(returnedValue).isEqualTo(aBoolean)92 verify(mockCallback).dispatchTouchEvent(motionEvent)93 }94 @Test95 fun `dispatchTouchEvent will pass a copy of the event to the gesture detector`() {96 // Given97 val motionEvent: MotionEvent = mock()98 val copyMotionEvent: MotionEvent = mock()99 val spyTest = spy(testedWrapper)100 doReturn(copyMotionEvent).`when`(spyTest).copyEvent(motionEvent)101 // When102 spyTest.dispatchTouchEvent(motionEvent)103 // Then104 verify(mockGestureDetector).onTouchEvent(copyMotionEvent)105 verify(copyMotionEvent).recycle()106 }107 @Test108 fun `menu item selection will trigger a Rum UserActionEvent`(forge: Forge) {109 // Given110 val returnValue = forge.aBool()111 val itemTitle = forge.aString()112 val featureId = forge.anInt()113 val itemId = forge.anInt()114 val itemResourceName = forge.aString()115 whenever(mockResources.getResourceEntryName(itemId)).thenReturn(itemResourceName)116 val menuItem: MenuItem = mock {117 whenever(it.itemId).thenReturn(itemId)118 whenever(it.title).thenReturn(itemTitle)119 }120 whenever(mockCallback.onMenuItemSelected(featureId, menuItem)).thenReturn(returnValue)121 // When122 assertThat(testedWrapper.onMenuItemSelected(featureId, menuItem)).isEqualTo(returnValue)123 // Then124 inOrder(mockCallback, mockRumMonitor) {125 verify(mockRumMonitor).addUserAction(126 eq(RumActionType.TAP),127 eq(targetName(menuItem, itemResourceName)),128 argThat {129 val targetClassName = menuItem.javaClass.canonicalName130 this[RumAttributes.ACTION_TARGET_CLASS_NAME] == targetClassName &&131 this[RumAttributes.ACTION_TARGET_RESOURCE_ID] == itemResourceName &&132 this[RumAttributes.ACTION_TARGET_TITLE] == itemTitle133 }134 )135 verify(mockCallback).onMenuItemSelected(featureId, menuItem)136 }137 }138 @Test139 fun `pressing back button will trigger specific user action event`(forge: Forge) {140 // Given141 val returnedValue = forge.aBool()142 whenever(mockCallback.dispatchKeyEvent(any())).thenReturn(returnedValue)143 val keyEvent = mockKeyEvent(KeyEvent.ACTION_UP, KeyEvent.KEYCODE_BACK)144 // When145 assertThat(testedWrapper.dispatchKeyEvent(keyEvent)).isEqualTo(returnedValue)146 // Then147 inOrder(mockRumMonitor, mockCallback) {148 verify(mockRumMonitor).addUserAction(RumActionType.CUSTOM, "back", emptyMap())149 verify(mockCallback).dispatchKeyEvent(keyEvent)150 }151 }152 @Test153 fun `pressing back button will trigger user action event only on ACTION_UP`(forge: Forge) {154 // Given155 val returnedValue = forge.aBool()156 whenever(mockCallback.dispatchKeyEvent(any())).thenReturn(returnedValue)157 val keyEvent = mockKeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_BACK)158 // When159 assertThat(testedWrapper.dispatchKeyEvent(keyEvent)).isEqualTo(returnedValue)160 // Then161 inOrder(mockRumMonitor, mockCallback) {162 verifyZeroInteractions(mockRumMonitor)163 verify(mockCallback).dispatchKeyEvent(keyEvent)164 }165 }166 @Test167 fun `pressing any other key except back button will do nothing`(forge: Forge) {168 // Given169 val returnedValue = forge.aBool()170 whenever(mockCallback.dispatchKeyEvent(any())).thenReturn(returnedValue)171 val keyCode = forge.anInt(min = 5)172 val keyEvent = mockKeyEvent(KeyEvent.ACTION_UP, keyCode)173 // When174 assertThat(testedWrapper.dispatchKeyEvent(keyEvent)).isEqualTo(returnedValue)175 // Then176 inOrder(mockRumMonitor, mockCallback) {177 verifyZeroInteractions(mockRumMonitor)178 verify(mockCallback).dispatchKeyEvent(keyEvent)179 }180 }181 // region Internal182 private fun mockKeyEvent(action: Int, keyCode: Int): KeyEvent {183 return mock {184 whenever(it.keyCode).thenReturn(keyCode)185 whenever(it.action).thenReturn(action)186 }187 }188 // endregion189}...
PowerMockitoTest.kt
Source:PowerMockitoTest.kt
1package com.lilong.androidunittest2import com.nhaarman.mockitokotlin2.*3import org.junit.Before4import org.junit.Test5import org.junit.runner.RunWith6import org.mockito.ArgumentMatchers.*7import org.mockito.Mock8import org.powermock.api.mockito.PowerMockito9import org.powermock.core.classloader.annotations.PrepareForTest10import org.powermock.modules.junit4.PowerMockRunner11/**12 * è¿éä¹ä¸éè¦ MockitoAnnotations.initAnnotationsï¼ç¨äºåè导è´é®é¢13 * [PowerMockRunner] å·²ç»å¤çäºæ³¨è§£14 */15@RunWith(PowerMockRunner::class)16@PrepareForTest(FCalculator::class)17class PowerMockitoTest {18 private val realCalculator = FCalculator()19 @Mock20 private lateinit var mockCalculator: FCalculator21 // å¨ä½¿ç¨ PowerMockRunner æ¶ï¼æ æ³ä½¿ç¨ @Spy 注解22 @Before23 fun setUp(){24 PowerMockito.mockStatic(FCalculator.Companion::class.java)25 }26 @Test27 fun stubbing() {28 // çå®å¯¹è±¡29 println(realCalculator.add(1, 2)) // çå®å¯¹è±¡ï¼return 330 // è§å® mock è§åï¼æ²¡å¨è§åå
çè°ç¨é½è¿åé»è®¤å¼ï¼è¿éæ¯031 // å¨è§åå
çè°ç¨ï¼è¿åè§åè§å®çå¼ï¼è¿å« stubbing32 whenever(mockCalculator.add(1, 2)).thenReturn(4)33 println(mockCalculator.add(1, 2)) // return 434 // 没æ stubbingï¼è¿å 035 println(mockCalculator.add(1, 3)) // return 036 // æ stubbing37 whenever(mockCalculator.add(anyInt(), anyInt())).thenReturn(100)38 println(mockCalculator.add(7, 9)) // return 10039 println(mockCalculator.add(1, 2)) // return 100ï¼è¦çäºä¹åç stubbing40 }41 @Test42 fun stubbingDoThrow() {43 whenever(mockCalculator.divide(anyFloat(), eq(1f))).doThrow(IllegalArgumentException())44 println(mockCalculator.divide(2f, 1f)) // throw IllegalArgumentException45 }46 @Test47 fun stubbingConsecutiveCallWithDifferentReturns() {48 // 注æ thenReturn æ¯è¿ç»è°ç¨çï¼å¦æä¸é´æå«ç wheneverï¼ä¼å¯¼è´åé¢ç thenReturn 设置è¦çæåé¢ç49 whenever(mockCalculator.add(1, 2)).thenReturn(1).thenReturn(2)50 println(mockCalculator.add(1, 2)) // return 151 println(mockCalculator.add(1, 2)) // return 252 }53 @Test54 fun stubbingWithThenAnswer() {55 whenever(mockCalculator.add(anyInt(), anyInt())).thenAnswer {56 it.arguments[0] as Int - it.arguments[1] as Int57 }58 println(mockCalculator.add(1, 2)) // return -159 }60 @Test61 fun verify() {62 mockCalculator.add(1, 3)63 verify(mockCalculator).add(1, 3) // verify ä¼æ£æµè°ç¨çæ¹æ³æ¬¡æ°ï¼åæ°ï¼ä»»ä½ä¸ä¸ªä¸ä¸è´é½ä¼ fail64 mockCalculator.add(1, 2)65 mockCalculator.add(1, 2)66 verify(mockCalculator, times(2)).add(1, 2)67 }68 /**69 * æ£æµ mock æ¯å¦æç
§è§å®ç顺åºæ§è¡äºæ¹æ³70 * åªéåå
¥å
³å¿çæ¹æ³71 * */72 @Test73 fun verifyInOrder() {74 mockCalculator.add(1, 2)75 mockCalculator.add(1, 3)76 inOrder(mockCalculator) {77 verify(mockCalculator).add(1, 2)78 verify(mockCalculator).add(1, 3)79 }80 }81 @Test82 fun verifyNeverHappen() {83 mockCalculator.add(1, 3)84 verify(mockCalculator, never()).add(1, 2)85 }86 @Test87 fun verifyNoMoreInteractions() {88 mockCalculator.add(1, 2)89 verify(mockCalculator).add(1, 2)90 verifyNoMoreInteractions(mockCalculator)91 }92 @Test93 fun verifyPrivate(){94 mockCalculator.executeMinus(1, 2)95 PowerMockito.verifyPrivate(mockCalculator).invoke("minus", 1, 2) // fails96 }97 @Test98 fun spyTest() {99 // 注æè¿éè¦ç¨ PowerMockito ç spyï¼å
¶å®çä¸è¡100 val spiedCalculator = PowerMockito.spy(FCalculator())101 println(spiedCalculator.add(1, 2)) // return 3102 whenever(spiedCalculator.add(1, 2)).thenReturn(10)103 println(spiedCalculator.add(1, 2)) // return 10104 println(spiedCalculator.add(1, 5)) // return 6105 }106 @Test107 fun testDoAnswer(){108 whenever(mockCalculator.ignite()).doAnswer {109 println("a")110 }111 mockCalculator.ignite()112 }113 @Test114 fun testMockStatic(){115 whenever(FCalculator.staticMethod()).doAnswer {116 println("1")117 }118 FCalculator.staticMethod()119 }120}...
GetStateByIdUseCaseTest.kt
Source:GetStateByIdUseCaseTest.kt
...78 spyList.add("two")79 Mockito.verify(spyList).add("one")80 Mockito.verify(spyList).add("two")81 //assertEquals(2, spyList.size)82 //objTest = SpyTest()83 val spyClass = Mockito.spy(SpyTest())84 //Mockito.`when`(objTest.doAnOperation()).thenReturn(3)85// Mockito.doNothing().`when`(objTest).doAnOperation()86// doReturn(3).`when`(objTest.doAnOperation())87// assertEquals(3, objTest.doAnOperation())88 }89 @Captor90 lateinit var argumentCaptor: ArgumentCaptor<Int>91 @Captor92 lateinit var argumentString: ArgumentCaptor<String>93 @Mock94 lateinit var mockTest: IntestCap95 @Test96 fun captureString() {97 mockTest.acarayEl16esmyCumple("27 años")98 Mockito.verify(mockTest).acarayEl16esmyCumple(argumentString.capture())99 assertEquals("27 años", argumentString.value)100 }101 @Test102 fun captorTest() {103 //mockList.add(1)104 //mockList.add("one")105 //Mockito.verify(mockList).add(arg.capture())106 //argumentCaptor = ArgumentCaptor.forClass(SpyTest::class.java)107 mockTest.doSomething(1)108 Mockito.verify(mockTest).doSomething(argumentCaptor.capture())109 assertEquals(1, argumentCaptor.value)110 //mySpyTest.operationArgs(1)111 //Mockito.verify(mySpyTest).operationArgs(argumentCaptor.capture())112 //assertEquals(2, argumentCaptor.value)113// val argumentList: ArgumentCaptor<ArrayList<String>> = ArgumentCaptor.forClass(ArrayList<String>)114// nameList.add("joel")115// Mockito.verify(nameList).add()116//117// val argument: ArgumentCaptor<SpyTest> = ArgumentCaptor.forClass(SpyTest::class.java)118// Mockito.verify(myCapTest).operationArgs(2)119// // verify(objTest).doSomething(argument.capture())120// assertEquals(3, argument.value.operationArgs(2))121 }122 @Mock123 var mockedList: ArrayList<Int> = arrayListOf()124 @Captor125 lateinit var argCaptor: ArgumentCaptor<Int>126 @Test127 fun whenUseCaptorAnnotation_thenTheSam() {128 mockedList.add(1)129 Mockito.verify(mockedList).add(argCaptor.capture())130 assertEquals(1, argCaptor.value)131 }...
DatadogGesturesTrackerTest.kt
Source:DatadogGesturesTrackerTest.kt
1/*2 * Unless explicitly stated otherwise all files in this repository are licensed under the Apache License Version 2.0.3 * This product includes software developed at Datadog (https://www.datadoghq.com/).4 * Copyright 2016-Present Datadog, Inc.5 */6package com.datadog.android.rum.internal.instrumentation.gestures7import android.app.Activity8import android.view.Window9import com.nhaarman.mockitokotlin2.any10import com.nhaarman.mockitokotlin2.doReturn11import com.nhaarman.mockitokotlin2.isA12import com.nhaarman.mockitokotlin2.mock13import com.nhaarman.mockitokotlin2.never14import com.nhaarman.mockitokotlin2.spy15import com.nhaarman.mockitokotlin2.verify16import com.nhaarman.mockitokotlin2.whenever17import org.junit.jupiter.api.BeforeEach18import org.junit.jupiter.api.Test19import org.junit.jupiter.api.extension.ExtendWith20import org.junit.jupiter.api.extension.Extensions21import org.mockito.Mock22import org.mockito.junit.jupiter.MockitoExtension23import org.mockito.junit.jupiter.MockitoSettings24import org.mockito.quality.Strictness25@Extensions(26 ExtendWith(MockitoExtension::class)27)28@MockitoSettings(strictness = Strictness.LENIENT)29internal class DatadogGesturesTrackerTest {30 lateinit var testedTracker: DatadogGesturesTracker31 @Mock32 lateinit var mockActivity: Activity33 @Mock34 lateinit var mockWindow: Window35 @Mock36 lateinit var mockGestureDetector: GesturesDetectorWrapper37 @BeforeEach38 fun `set up`() {39 testedTracker =40 DatadogGesturesTracker(emptyArray())41 whenever(mockActivity.window).thenReturn(mockWindow)42 }43 @Test44 fun `will start tracking the activity`() {45 // When46 val spyTest = spy(testedTracker)47 doReturn(mockGestureDetector)48 .whenever(spyTest)49 .generateGestureDetector(mockActivity, mockWindow)50 spyTest.startTracking(mockWindow, mockActivity)51 // Then52 verify(mockWindow).callback = isA<WindowCallbackWrapper>()53 }54 @Test55 fun `will stop tracking the activity`() {56 // Given57 whenever(mockWindow.callback)58 .thenReturn(59 WindowCallbackWrapper(60 NoOpWindowCallback(),61 mockGestureDetector62 )63 )64 // When65 testedTracker.stopTracking(mockWindow, mockActivity)66 // Then67 verify(mockWindow).callback = null68 }69 @Test70 fun `stop tracking the activity will restore the previous callback if was not null`() {71 // Given72 val previousCallback: Window.Callback = mock()73 whenever(mockWindow.callback)74 .thenReturn(75 WindowCallbackWrapper(76 previousCallback,77 mockGestureDetector78 )79 )80 // When81 testedTracker.stopTracking(mockWindow, mockActivity)82 // Then83 verify(mockWindow).callback = previousCallback84 }85 @Test86 fun `stop will do nothing if the activity was not tracked`() {87 // When88 testedTracker.stopTracking(mockWindow, mockActivity)89 // Then90 verify(mockWindow, never()).callback = any()91 }92 @Test93 fun `will not track an activity with no decor view`() {94 // Given95 whenever(mockWindow.decorView).thenReturn(null)96 // Then97 verify(mockWindow, never()).callback = any()98 }99}...
SpyTestCls.kt
Source:SpyTestCls.kt
1package io.mockk.it2import io.mockk.every3import io.mockk.spyk4import kotlin.test.*5class SpyTest {6 @Test7 fun propertyInitialized() {8 val executed = arrayOf(false, false, false, false)9 val spyObj = spyk(SpyTestCls(executed))10 assertNotNull(spyObj.someReference)11 }12 @Test13 fun simpleSuperCall() {14 val executed = arrayOf(false, false, false, false)15 val spyObj = spyk(SpyTestCls(executed))16 every {17 spyObj.doSomething()18 } answers {19 callOriginal()20 }21 spyObj.doSomething()22 assertTrue(executed[0])23 assertTrue(executed[1])24 assertFalse(executed[2])25 assertFalse(executed[3])26 }27 @Test28 fun overrideCallOriginal() {29 val executed = arrayOf(false, false, false, false)30 val spyObj = spyk(SpyTestCls(executed))31 every {32 spyObj.computeSomething(1)33 } returns null34 assertNull(spyObj.computeSomething(1))35 assertFalse(executed[0])36 assertFalse(executed[1])37 assertFalse(executed[2])38 assertFalse(executed[3])39 }40 @Test41 fun secondSimpleSuperCall() {42 val executed = arrayOf(false, false, false, false)43 val spyObj = spyk(SpyTestCls(executed))44 every {45 spyObj.computeSomething(2)46 } answers { callOriginal()?.plus(4) }47 assertEquals(11, spyObj.computeSomething(2))48 assertFalse(executed[0])49 assertFalse(executed[1])50 assertTrue(executed[2])51 assertTrue(executed[3])52 }53 @Test54 fun notMockedCall() {55 val executed = arrayOf(false, false, false, false)56 val spyObj = spyk(SpyTestCls(executed))57 assertEquals(8, spyObj.computeSomething(3))58 assertFalse(executed[0])59 assertFalse(executed[1])60 assertTrue(executed[2])61 assertTrue(executed[3])62 }63 /**64 * See issue #9565 */66 @Test67 fun chainedCalls() {68 val mocking = spyk(ChainedCallsCls())69 every { mocking.bar(any()) } returns "FOO MOCKED"70 println(mocking.bar("hello"))71 }72 @Test73 fun chainedCalls2() {74 val mocking = spyk(ChainedCallsCls())75 every { mocking.bar2() } returns "FOO MOCKED"76 println(mocking.bar2())77 }78 class ChainedCallsCls {79 fun getInterface(list: List<Boolean>) = listOf(true)80 fun bar(t: String, list: List<Boolean> = getInterface(listOf(false))): String {81 return "FOO"82 }83 fun bar2(list: List<Boolean> = getInterface(listOf(false))): String {84 return "FOO"85 }86 }87 open class BaseTestCls(val someReference: String, val executed: Array<Boolean>) {88 open fun doSomething() {89 executed[0] = true90 }91 open fun computeSomething(a: Int): Int? {92 executed[2] = true93 return 2294 }95 }96 class SpyTestCls(executed: Array<Boolean>) : BaseTestCls("A spy", executed) {97 override fun doSomething() {98 executed[1] = true99 super.doSomething()100 }101 override fun computeSomething(a: Int): Int? {102 executed[3] = true103 super.computeSomething(a)104 return 5 + a105 }106 }107}...
LoginPresenterTest.kt
Source:LoginPresenterTest.kt
1package com.lain.calculator.mockito2import org.junit.Assert3import org.junit.Assert.*4import org.junit.Before5import org.junit.Test6import org.junit.runner.RunWith7import org.mockito.Mock8import org.mockito.Mockito.*9import org.mockito.Spy10import org.mockito.junit.MockitoJUnitRunner11import java.lang.RuntimeException12import org.mockito.Mockito.`when` as wheen13@RunWith(MockitoJUnitRunner::class)14class LoginPresenterTest{15 @Mock16 private lateinit var view: Login.View17 @Mock18 private lateinit var model: Login.Model19 private lateinit var presenter: LoginPresenter20 @Before21 fun setup(){22 presenter = LoginPresenter(view)23 }24 @Test25 fun showShowErrorMessageWhenTheUserOrPasswordIsIncorrectTest(){26 wheen(view.userName()).thenReturn("Maria")27 wheen(view.password()).thenReturn("1273891237")28 presenter.validUser(view.userName(), view.password())29 30 verify(view).error()31 }32 @Test33 fun shouldCallUserValidWhenUserAndPasswordIsRightTest(){34 //Hace una llamada real al metodo35 wheen(view.userName()).thenReturn("andrea")36 wheen(view.password()).thenReturn("1234")37 assertEquals("andrea", view.userName())38 assertEquals("1234", view.password())39 presenter.validUser(40 user = view.userName(),41 password = view.password()42 )43 verify(view).userValid()44 }45 @Test46 fun shouldThrowingException(){47 wheen(view.userName()).thenThrow(RuntimeException::class.java)48 try {49 view.userName()50 }catch (runtTimeException: RuntimeException){51 }52 }53 @Test54 fun shouldCallUserValidWhenUserAndPasswordIsRightDoReturnTest(){55 //No hace una llamada real al metodo56 doReturn("andrea").`when`(view).userName()57 assertEquals("andrea", view.userName())58 }59 @Test60 fun shouldCallUserValidWhenUserAndPasswordIsRightTest2(){61 //Hace una llamada real al metodo62 wheen(view.userName()).thenReturn("andrea")63 wheen(view.password()).thenReturn("1234")64 assertEquals("andrea", view.userName())65 assertEquals("1234", view.password())66 presenter.validUser(67 user = view.userName(),68 password = view.password()69 )70 verify(view).userValid()71 verify(view, times(1)).userValid()72 verify(view, never()).userValid()73 //Pasa si se llama al menos 1 vez74 verify(view, atLeast(4)).userValid()75 //Pasa si se llama menos de 7 veces76 verify(view, atMost(7)).userValid()77 //Solo 1 vez78 verify(view, only()).userValid()79 }80 @Mock81 val mockList = mutableListOf<String>()82 @Spy83 val spyList = mutableListOf<String>()84 @Test85 fun spyTest(){86 spyList.add("one")87 spyList.add("two")88 verify(spyList).add("one")89 verify(spyList).add("two")90 assertEquals(2, spyList.size)91 }92 @Test93 fun mockTest(){94 mockList.add("one")95 mockList.add("two")96 verify(mockList).add("one")97 verify(mockList).add("two")98 assertEquals(2, mockList.size)99 }100}...
TestMyClass.kt
Source:TestMyClass.kt
1import mymockito.MyClass2import org.junit.*3import org.junit.Assert.*4import org.junit.rules.ExpectedException5import org.mockito.ArgumentCaptor6import org.mockito.ArgumentMatchers7import org.mockito.Captor8import org.mockito.Mockito.*9import java.lang.IllegalArgumentException10import java.util.*11class TestMyClass {12 @Test13 fun testGetUnique()14 {15 val mock : MyClass = mock(MyClass::class.java)16 `when`(mock.getUniqueId()).thenReturn(43)17 assertEquals(43, mock.getUniqueId())18 }19 @Test20 fun testTwoValues()21 {22 val iter = mock(Iterator::class.java) as Iterator<String>23 `when`(iter.next()).thenReturn("Hello").thenReturn("World")24 val result = iter.next() + " " + iter.next()25 assertEquals(result, "Hello World")26 }27 @get:Rule28 var exceptionRule = ExpectedException.none()29 @Test30 fun testThrowAndCatch()31 {32 val mock = mock(MyClass::class.java)33 `when`(mock.getUniqueId()).thenThrow(IllegalArgumentException("Typo"))34 exceptionRule.expect(IllegalArgumentException::class.java)35 exceptionRule.expectMessage("Typo")36 mock.getUniqueId()37 }38 @Test39 fun testOrderAndNumberOfTimes()40 {41 val mock = mock(MyClass::class.java)42 `when`(mock.getUniqueId()).thenReturn(43)43 val inOrder = inOrder(mock)44 mock.testing(12)45 mock.getUniqueId()46 mock.getUniqueId()47 verify(mock).testing(ArgumentMatchers.eq(12))48 verify(mock, times(2)).getUniqueId()49 verify(mock, atLeastOnce()).getUniqueId()50 verify(mock, never()).someMethod("123")51 verify(mock, atLeast(1)).getUniqueId()52 verify(mock, atMost(10)).getUniqueId()53 inOrder.verify(mock).testing(12)54 inOrder.verify(mock, times(2)).getUniqueId()55 verifyNoMoreInteractions(mock)56 }57 @Captor58 var stringCaptor = ArgumentCaptor.forClass(String::class.java)59 class MockitoHelper60 {61 fun <T> capture(captor: ArgumentCaptor<T>) : T = captor.capture()62 }63 @Test64 fun spyTest()65 {66 var list = LinkedList<String>()67 val spy = spy(list)68 spy.add("hello")69 verify(spy).add(MockitoHelper().capture(stringCaptor))70 assertTrue(stringCaptor.value == "hello")71 }72 @Before73 fun init()74 {75 println("init")76 }77 @After78 fun tearDown()79 {80 println("after")81 }82 companion object {83 @BeforeClass @JvmStatic84 fun beforeAll()85 {86 println("before all")87 }88 @AfterClass @JvmStatic89 fun afterAll()90 {91 println("after all")92 }93 }94}...
SpyTest.kt
Source:SpyTest.kt
...3import mobx.core.spy4import org.assertj.core.api.Assertions.assertThat5import org.spekframework.spek2.Spek6import org.spekframework.spek2.style.specification.describe7object SpyTest : Spek({8 describe("spy test") {9 var spyPayload: Any? = null10 val disposable = spy {11 spyPayload = it12 }13 it("should receive payload from actions until disposed") {14 action("testPayload") {}15 assertThat(spyPayload).isEqualTo("testPayload")16 disposable.dispose()17 action("new test payload") {}18 assertThat(spyPayload).isEqualTo("testPayload")19 }20 }21})...
SpyTest
Using AI Code Generation
1import test.SpyTest;2public class SpyTestUser {3public static void main(String[] args) {4SpyTest test = new SpyTest();5test.test();6}7}8package test;9public class SpyTest {10public void test() {11System.out.println("I am in test method");12}13}
SpyTest
Using AI Code Generation
1import test.SpyTest;2import test.SpyTest;3import test.SpyTest;4public class SpyTest {5 private String name;6 private int id;7 private String codeName;8 private static int spyCount = 0;9 public Spy(int spyId, String spyName, String spyCodeName) {10 this.id = spyId;11 this.name = spyName;12 this.codeName = spyCodeName;13 spyCount++;14 System.out.println("Spy " + this.id + " : " + this.name + " has been created.");15 System.out.println("Code Number : " + this.codeName);16 System.out.println("There are " + spyCount + " spies in total.");17 }18 public void die() {19 spyCount--;20 System.out.println("Spy " + this.id + " : " + this.name + " has been eliminated.");21 System.out.println("There are " + spyCount + " spies in total.");22 }23 public void setCodeName(String newCodeName) {24 this.codeName = newCodeName;25 System.out.println("Spy " + this.id + " : " + this.name + " has a new codename.");26 System.out.println("New Code Name : " + this.codeName);27 }28 public static void main(String[] args) {29 Spy spy1 = new Spy(1, "James Bond", "007");30 Spy spy2 = new Spy(2, "Jason Bourne", "008");31 spy2.die();32 spy1.setCodeName("006");33 }34}
SpyTest
Using AI Code Generation
1import test.SpyTest;2import test.SpyTest;3import test.SpyTest;4public class SpyTest {5 public static void main(String[] args) {6 Spy spy1 = new Spy(1);7 Spy spy2 = new Spy(2);8 Spy spy3 = new Spy(3);9 Spy spy4 = new Spy(4);10 Spy spy5 = new Spy(5);11 spy3.die();12 spy4.die();13 spy5.die();14 }15}16public class Spy {17 private int spyID;18 private static int spyCount = 0;19 public Spy(int spyID) {20 this.spyID = spyID;21 spyCount++;22 System.out.println("Spy " + this.spyID + " has been created.");23 System.out.println("There are " + spyCount + " spies.");24 }25 public void die() {26 System.out.println("Spy " + this.spyID + " has been detected and eliminated.");27 spyCount--;28 System.out.println("There are " + spyCount + " spies.");29 }30}
SpyTest
Using AI Code Generation
1import java.util.*;2{3public static void main(String args[])4{5Scanner sc=new Scanner(System.in);6int n=sc.nextInt();7}8}
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!!