Best Mockito-kotlin code snippet using org.mockito.kotlin.Mockito.validateMockitoUsage
AmazonLaunchTemplateHandlerTest.kt
Source:AmazonLaunchTemplateHandlerTest.kt
...46import com.nhaarman.mockito_kotlin.eq47import com.nhaarman.mockito_kotlin.mock48import com.nhaarman.mockito_kotlin.reset49import com.nhaarman.mockito_kotlin.times50import com.nhaarman.mockito_kotlin.validateMockitoUsage51import com.nhaarman.mockito_kotlin.verify52import com.nhaarman.mockito_kotlin.verifyNoMoreInteractions53import com.nhaarman.mockito_kotlin.whenever54import java.time.Clock55import java.time.Instant56import java.time.ZoneOffset57import org.junit.jupiter.api.AfterEach58import org.junit.jupiter.api.BeforeEach59import org.junit.jupiter.api.Test60import org.springframework.context.ApplicationEventPublisher61import strikt.api.expectThat62import strikt.assertions.isEqualTo63import strikt.assertions.isFalse64import strikt.assertions.isNull65import strikt.assertions.isTrue66object AmazonLaunchTemplateHandlerTest {67 private val aws = mock<AWS>()68 private val resourceRepository = mock<ResourceTrackingRepository>()69 private val resourceStateRepository = mock<ResourceStateRepository>()70 private val taskTrackingRepository = mock<TaskTrackingRepository>()71 private val resourceOwnerResolver = mock<ResourceOwnerResolver<AmazonLaunchTemplate>>()72 private val clock = Clock.fixed(Instant.now(), ZoneOffset.UTC)73 private val applicationEventPublisher = mock<ApplicationEventPublisher>()74 private val orcaService = mock<OrcaService>()75 private val resourceUseTrackingRepository = mock<ResourceUseTrackingRepository>()76 private val dynamicConfigService = mock<DynamicConfigService>()77 private val notificationQueue = mock<NotificationQueue>()78 private val rulesEngine = mock<ResourceRulesEngine>()79 private val ruleAndViolationPair = Pair<Rule, List<Summary>>(mock(), listOf(Summary("violate rule", ruleName = "rule")))80 private val workConfiguration = WorkConfigurationTestHelper81 .generateWorkConfiguration(resourceType = LAUNCH_TEMPLATE, cloudProvider = AWS)82 private val params = Parameters(83 account = workConfiguration.account.accountId!!,84 region = workConfiguration.location,85 environment = workConfiguration.account.environment86 )87 private val subject = AmazonLaunchTemplateHandler(88 clock = clock,89 registry = NoopRegistry(),90 rulesEngine = rulesEngine,91 notifier = mock(),92 resourceTrackingRepository = resourceRepository,93 resourceStateRepository = resourceStateRepository,94 taskTrackingRepository = taskTrackingRepository,95 exclusionPolicies = listOf(),96 resourceOwnerResolver = resourceOwnerResolver,97 applicationEventPublisher = applicationEventPublisher,98 aws = aws,99 orcaService = orcaService,100 resourceUseTrackingRepository = resourceUseTrackingRepository,101 swabbieProperties = SwabbieProperties().also { it.schedule.enabled = false },102 dynamicConfigService = dynamicConfigService,103 notificationQueue = notificationQueue,104 applicationUtils = ApplicationUtils(emptyList())105 )106 private const val user = "test@netflix.com"107 private val lt1 = AmazonLaunchTemplate(108 launchTemplateId = "app-v001-001",109 launchTemplateName = "app-v001-001",110 createdTime = clock.millis()111 )112 private val lt2 = AmazonLaunchTemplate(113 launchTemplateId = "app-v002-002",114 launchTemplateName = "app-v002-002",115 createdTime = clock.millis()116 )117 @BeforeEach118 fun setup() {119 lt1.details.clear()120 lt2.details.clear()121 whenever(resourceOwnerResolver.resolve(any())) doReturn user122 whenever(aws.getLaunchTemplates(params)) doReturn listOf(lt1, lt2)123 whenever(dynamicConfigService.getConfig(any(), any(), eq(workConfiguration.maxItemsProcessedPerCycle))) doReturn124 workConfiguration.maxItemsProcessedPerCycle125 whenever(dynamicConfigService.getConfig(any(), any(), eq(workConfiguration.deleteSpreadMs))) doReturn126 workConfiguration.deleteSpreadMs127 }128 @AfterEach129 fun cleanup() {130 validateMockitoUsage()131 reset(aws, resourceRepository, applicationEventPublisher, resourceOwnerResolver, rulesEngine, taskTrackingRepository)132 }133 @Test134 fun `should handle launch templates`() {135 whenever(rulesEngine.getRules(workConfiguration)) doReturn listOf(ruleAndViolationPair.first)136 expectThat(subject.handles(workConfiguration)).isTrue()137 whenever(rulesEngine.getRules(workConfiguration)) doReturn emptyList<Rule>()138 expectThat(subject.handles(workConfiguration)).isFalse()139 }140 @Test141 fun `should get launch templates`() {142 expectThat(subject.getCandidates(workConfiguration)!!.count()).isEqualTo(2)143 }144 @Test...
AmazonAutoScalingGroupHandlerTest.kt
Source:AmazonAutoScalingGroupHandlerTest.kt
...45import com.nhaarman.mockito_kotlin.eq46import com.nhaarman.mockito_kotlin.mock47import com.nhaarman.mockito_kotlin.reset48import com.nhaarman.mockito_kotlin.times49import com.nhaarman.mockito_kotlin.validateMockitoUsage50import com.nhaarman.mockito_kotlin.verify51import com.nhaarman.mockito_kotlin.verifyNoMoreInteractions52import com.nhaarman.mockito_kotlin.whenever53import java.time.Clock54import java.time.Instant55import java.time.ZoneOffset56import org.junit.jupiter.api.AfterEach57import org.junit.jupiter.api.BeforeEach58import org.junit.jupiter.api.Test59import org.springframework.context.ApplicationEventPublisher60import strikt.api.expectThat61import strikt.assertions.isEqualTo62import strikt.assertions.isFalse63import strikt.assertions.isTrue64object AmazonAutoScalingGroupHandlerTest {65 private val aws = mock<AWS>()66 private val resourceRepository = mock<ResourceTrackingRepository>()67 private val resourceStateRepository = mock<ResourceStateRepository>()68 private val taskTrackingRepository = mock<TaskTrackingRepository>()69 private val resourceOwnerResolver = mock<ResourceOwnerResolver<AmazonAutoScalingGroup>>()70 private val clock = Clock.fixed(Instant.now(), ZoneOffset.UTC)71 private val applicationEventPublisher = mock<ApplicationEventPublisher>()72 private val orcaService = mock<OrcaService>()73 private val resourceUseTrackingRepository = mock<ResourceUseTrackingRepository>()74 private val dynamicConfigService = mock<DynamicConfigService>()75 private val notificationQueue = mock<NotificationQueue>()76 private val rulesEngine = mock<ResourceRulesEngine>()77 private val ruleAndViolationPair = Pair<Rule, List<Summary>>(mock(), listOf(Summary("violate rule", ruleName = "rule")))78 private val workConfiguration = WorkConfigurationTestHelper79 .generateWorkConfiguration(resourceType = SERVER_GROUP, cloudProvider = AWS)80 private val params = Parameters(81 account = workConfiguration.account.accountId!!,82 region = workConfiguration.location,83 environment = workConfiguration.account.environment84 )85 private val subject = AmazonAutoScalingGroupHandler(86 clock = clock,87 registry = NoopRegistry(),88 rulesEngine = rulesEngine,89 notifier = mock(),90 resourceTrackingRepository = resourceRepository,91 resourceStateRepository = resourceStateRepository,92 taskTrackingRepository = taskTrackingRepository,93 exclusionPolicies = listOf(),94 resourceOwnerResolver = resourceOwnerResolver,95 applicationEventPublisher = applicationEventPublisher,96 aws = aws,97 orcaService = orcaService,98 resourceUseTrackingRepository = resourceUseTrackingRepository,99 swabbieProperties = SwabbieProperties().also { it.schedule.enabled = false },100 dynamicConfigService = dynamicConfigService,101 notificationQueue = notificationQueue,102 applicationUtils = ApplicationUtils(emptyList())103 )104 private const val user = "test@netflix.com"105 private val sg1 = AmazonAutoScalingGroup(106 autoScalingGroupName = "testapp-v001",107 instances = listOf(),108 loadBalancerNames = listOf(),109 createdTime = clock.millis()110 )111 private val sg2 = AmazonAutoScalingGroup(112 autoScalingGroupName = "app-v001",113 instances = listOf(),114 loadBalancerNames = listOf(),115 createdTime = clock.millis()116 )117 @BeforeEach118 fun setup() {119 whenever(resourceOwnerResolver.resolve(any())) doReturn user120 whenever(aws.getServerGroups(params)) doReturn listOf(sg1, sg2)121 whenever(dynamicConfigService.getConfig(any(), any(), eq(workConfiguration.maxItemsProcessedPerCycle))) doReturn122 workConfiguration.maxItemsProcessedPerCycle123 whenever(dynamicConfigService.getConfig(any(), any(), eq(workConfiguration.deleteSpreadMs))) doReturn124 workConfiguration.deleteSpreadMs125 }126 @AfterEach127 fun cleanup() {128 validateMockitoUsage()129 reset(aws, resourceRepository, applicationEventPublisher, resourceOwnerResolver, rulesEngine, taskTrackingRepository)130 }131 @Test132 fun `should handle server groups`() {133 whenever(rulesEngine.getRules(workConfiguration)) doReturn listOf(ruleAndViolationPair.first)134 expectThat(subject.handles(workConfiguration)).isTrue()135 whenever(rulesEngine.getRules(workConfiguration)) doReturn emptyList<Rule>()136 expectThat(subject.handles(workConfiguration)).isFalse()137 }138 @Test139 fun `should get server groups`() {140 expectThat(subject.getCandidates(workConfiguration)!!.count()).isEqualTo(2)141 }142 @Test...
PrefsUtilTest.kt
Source:PrefsUtilTest.kt
2import android.content.SharedPreferences3import com.nhaarman.mockito_kotlin.any4import com.nhaarman.mockito_kotlin.mock5import com.nhaarman.mockito_kotlin.never6import com.nhaarman.mockito_kotlin.validateMockitoUsage7import com.nhaarman.mockito_kotlin.verify8import com.nhaarman.mockito_kotlin.whenever9import junit.framework.Assert.assertEquals10import org.junit.After11import org.junit.Test12import org.junit.Before13class PrefsUtilTest {14 private val store: SharedPreferences = mock()15 private val editor: SharedPreferences.Editor = mock()16 private val idGenerator: DeviceIdGenerator = mock()17 private val uuidGenerator: UUIDGenerator = mock()18 private val subject: PrefsUtil = PrefsUtil(store, idGenerator, uuidGenerator)19 @Before20 fun setUpSharedPrefs() {21 whenever(store.edit()).thenReturn(editor)22 whenever(editor.putString(any(), any())).thenReturn(editor)23 whenever(editor.remove(any())).thenReturn(editor)24 whenever(editor.clear()).thenReturn(editor)25 }26 @Test27 fun getDeviceId_qaRandomiseNotSet_nothingStored() {28 // Arrange29 whenever(idGenerator.generateId()).thenReturn(STATIC_DEVICE_ID)30 whenever(store.getBoolean(PrefsUtil.KEY_IS_DEVICE_ID_RANDOMISED, false))31 .thenReturn(false)32 whenever(store.getString(PrefsUtil.KEY_PRE_IDV_DEVICE_ID, ""))33 .thenReturn("")34 // Act35 val id = subject.deviceId36 // Assert37 assertEquals(id, STATIC_DEVICE_ID)38 verify(store).getBoolean(PrefsUtil.KEY_IS_DEVICE_ID_RANDOMISED, false)39 verify(uuidGenerator, never()).generateUUID()40 }41 @Test42 fun getDeviceId_qaRandomiseIsSet_nothingStored() {43 // Arrange44 whenever(idGenerator.generateId()).thenReturn(STATIC_DEVICE_ID)45 whenever(uuidGenerator.generateUUID()).thenReturn(RANDOM_DEVICE_ID)46 whenever(store.getBoolean(PrefsUtil.KEY_IS_DEVICE_ID_RANDOMISED, false))47 .thenReturn(true)48 whenever(store.getString(PrefsUtil.KEY_PRE_IDV_DEVICE_ID, ""))49 .thenReturn("")50 // Act51 val id = subject.deviceId52 // Assert53 assertEquals(id, RANDOM_DEVICE_ID)54 verify(store).getBoolean(PrefsUtil.KEY_IS_DEVICE_ID_RANDOMISED, false)55 verify(uuidGenerator).generateUUID()56 }57 @Test58 fun getDeviceId_qaRandomiseNotSet_returnStored() {59 // Arrange60 whenever(store.getBoolean(PrefsUtil.KEY_IS_DEVICE_ID_RANDOMISED, false))61 .thenReturn(false)62 whenever(store.getString(PrefsUtil.KEY_PRE_IDV_DEVICE_ID, ""))63 .thenReturn(STATIC_DEVICE_ID)64 // Act65 val id = subject.deviceId66 // Assert67 assertEquals(id, STATIC_DEVICE_ID)68 verify(store).getBoolean(PrefsUtil.KEY_IS_DEVICE_ID_RANDOMISED, false)69 verify(uuidGenerator, never()).generateUUID()70 verify(idGenerator, never()).generateId()71 }72 @Test73 fun getDeviceId_qaRandomiseIsSet_valueStored_returnRandomised() {74 // Arrange75 whenever(idGenerator.generateId()).thenReturn(STATIC_DEVICE_ID)76 whenever(uuidGenerator.generateUUID()).thenReturn(RANDOM_DEVICE_ID)77 whenever(store.getBoolean(PrefsUtil.KEY_IS_DEVICE_ID_RANDOMISED, false))78 .thenReturn(true)79 // Act80 val id = subject.deviceId81 // Assert82 assertEquals(id, RANDOM_DEVICE_ID)83 verify(store).getBoolean(PrefsUtil.KEY_IS_DEVICE_ID_RANDOMISED, false)84 verify(store, never()).getString(PrefsUtil.KEY_PRE_IDV_DEVICE_ID, "")85 verify(uuidGenerator).generateUUID()86 }87 @Test88 fun getSelectedCrypto_corruptedStore_returnDefault() {89 // Arrange90 whenever(store.getString(PrefsUtil.KEY_SELECTED_CRYPTO, PrefsUtil.DEFAULT_CRYPTO_CURRENCY.name))91 .thenReturn("NOPE")92 // Act93 val currency = subject.selectedCryptoCurrency94 // Arrange95 assertEquals(currency, PrefsUtil.DEFAULT_CRYPTO_CURRENCY)96 verify(editor).remove(PrefsUtil.KEY_SELECTED_CRYPTO)97 }98 companion object {99 private const val STATIC_DEVICE_ID = "12345678901234567890"100 private const val RANDOM_DEVICE_ID = "84962066204735275920"101 }102 @After103 fun validate() {104 validateMockitoUsage()105 }106}...
MockitoHelper.kt
Source:MockitoHelper.kt
...47fun <T> spy(value: T): T = Mockito.spy(value)!!48fun <T> stub(methodCall: T): DeprecatedOngoingStubbing<T> = Mockito.stub(methodCall)!!49fun timeout(millis: Long): VerificationWithTimeout = Mockito.timeout(millis)!!50fun times(numInvocations: Int): VerificationMode = Mockito.times(numInvocations)!!51fun validateMockitoUsage() = Mockito.validateMockitoUsage()52fun <T> verify(mock: T): T = Mockito.verify(mock)!!53fun <T> verify(mock: T, mode: VerificationMode): T = Mockito.verify(mock, mode)!!54fun <T> verifyNoMoreInteractions(vararg mocks: T) = Mockito.verifyNoMoreInteractions(*mocks)55fun verifyZeroInteractions(vararg mocks: Any) = Mockito.verifyZeroInteractions(*mocks)56fun <T> whenever(methodCall: T): OngoingStubbing<T> = Mockito.`when`(methodCall)!!57fun withSettings(): MockSettings = Mockito.withSettings()!!58fun <T> Stubber.whenever(mock: T) : T = `when`(mock)...
CalendarSharingTest.kt
Source:CalendarSharingTest.kt
...10import org.mockito.ArgumentMatcher11import org.mockito.kotlin.argThat12import org.mockito.kotlin.mock13import org.mockito.kotlin.never14import org.mockito.kotlin.validateMockitoUsage15import org.mockito.kotlin.verify16/**17 * Covers [CalendarSharing.addToCalendar].18 * Does not cover Android framework routines such [Context.startActivity].19 */20class CalendarSharingTest {21 private val context = mock<Context>()22 private val onFailure: () -> Unit = mock()23 @Test24 fun `addToCalendar composes and emits a calendar insert intent`() {25 val session = createSession()26 CalendarSharing(context, FakeComposer, onFailure).addToCalendar(session)27 verify(context).startActivity(argThat(InsertIntentMatcher()))28 verify(onFailure, never()).invoke()29 }30 @After31 fun validate() {32 validateMockitoUsage()33 }34 private class InsertIntentMatcher : ArgumentMatcher<Intent> {35 override fun matches(intent: Intent) = intent.action == Intent.ACTION_INSERT &&36 intent.toUri(0) == "#Intent;action=android.intent.action.INSERT;" +37 "S.description=Lorem%20ipsum%20dolor;l.beginTime=1439478900000;l.endTime=1439480700000;" +38 "S.title=Title;S.eventLocation=Room;end" &&39 intent.extras != null && matchesExtras(intent.extras!!)40 private fun matchesExtras(extras: Bundle) =41 extras.get(CalendarContract.Events.TITLE) == "Title" &&42 extras.get(CalendarContract.Events.DESCRIPTION) == "Lorem ipsum dolor" &&43 extras.get(CalendarContract.Events.EVENT_LOCATION) == "Room" &&44 extras.get(CalendarContract.EXTRA_EVENT_BEGIN_TIME) == 1439478900000L &&45 extras.get(CalendarContract.EXTRA_EVENT_END_TIME) == 1439480700000L46 override fun toString() = "Session intent does not match."...
EmployeeViewModelTest.kt
Source:EmployeeViewModelTest.kt
...8import com.example.employeedirectoryapp.network.EmployeeService9import com.example.employeedirectoryapp.utils.MockUtil.mockEmployee10import com.example.employeedirectoryapp.utils.MockUtil.mockEmployeeList11import com.nhaarman.mockitokotlin2.mock12import com.nhaarman.mockitokotlin2.validateMockitoUsage13import junit.framework.TestCase.assertEquals14import kotlinx.coroutines.ExperimentalCoroutinesApi15import kotlinx.coroutines.test.runTest16import org.junit.After17import org.junit.Before18import org.junit.Rule19import org.junit.Test20import org.mockito.Mockito.`when`21import kotlin.time.DurationUnit22import kotlin.time.ExperimentalTime23import kotlin.time.toDuration24@ExperimentalTime25@ExperimentalCoroutinesApi26class EmployeeViewModelTest {27 private lateinit var viewModel: EmployeeViewModel28 private lateinit var repo: EmployeeRepository29 private val service: EmployeeService = mock()30 @get:Rule31 val task = InstantTaskExecutorRule()32 @get:Rule33 var coroutineRule = MainCoroutineRule()34 @Before35 fun setup() {36 repo = EmployeeRepository(service)37 viewModel = EmployeeViewModel(repo, coroutineRule.testDispatcher)38 }39 @After40 fun validate() {41 validateMockitoUsage() // Ensure error appears in the correct test method42 }43 @Test44 fun `fetch employees from network`() = runTest {45 val mockData = mockEmployeeList()46 `when`(repo.fetchEmployees()).thenReturn(NetworkResult.Success(EmployeeResponse(mockData)))47 viewModel.fetchEmployees()48 viewModel.employeesFlow.test(2.toDuration(DurationUnit.SECONDS)) {49 val expectItem = awaitItem()50 assertEquals(expectItem[0].full_name, mockEmployee().full_name)51 assertEquals(expectItem[0].team, mockEmployee().team)52 assertEquals(expectItem, mockData)53 }54 }55}...
UserRepositoryTestCase.kt
Source:UserRepositoryTestCase.kt
...59 }60 @After61 fun after(){62 Dispatchers.resetMain()63 Mockito.validateMockitoUsage();64 }65}...
Mockito.kt
Source:Mockito.kt
...24 */25package com.uce.kotlin.lib1.mockito26import org.mockito.MockingDetails27import org.mockito.Mockito28fun validateMockitoUsage() {29 Mockito.validateMockitoUsage()30}31fun <T> reset(vararg mocks: T) {32 Mockito.reset(*mocks)33}34fun mockingDetails(toInspect: Any): MockingDetails {35 return Mockito.mockingDetails(toInspect)!!36}...
validateMockitoUsage
Using AI Code Generation
1import org.mockito.kotlin.validateMockitoUsage2class MockitoTest {3fun validate() {4validateMockitoUsage()5}6fun test() {7}8}9import org.mockito.Mockito10class MockitoTest {11fun validate() {
validateMockitoUsage
Using AI Code Generation
1fun `test mockito usage`() {2val mock = mock<SomeInterface>()3mock.doSomething()4validateMockitoUsage()5}6fun `test mockito usage`() {7val mock = mock<SomeInterface>()8mock.doSomething()9validateMockitoUsage()10}11fun `test mockito usage`() {12val mock = mock<SomeInterface>()13mock.doSomething()14org.mockito.kotlin.Mockito.validateMockitoUsage()15}16fun `test mockito usage`() {17val mock = mock<SomeInterface>()18mock.doSomething()19org.mockito.kotlin.Mockito.validateMockitoUsage()20}21fun `test mockito usage`() {22val mock = mock<SomeInterface>()23mock.doSomething()24org.mockito.kotlin.Mockito.validateMockitoUsage()25}26fun `test mockito usage`() {27val mock = mock<SomeInterface>()28mock.doSomething()29org.mockito.kotlin.Mockito.validateMockitoUsage()30}31fun `test mockito usage`() {32val mock = mock<SomeInterface>()33mock.doSomething()34org.mockito.kotlin.Mockito.validateMockitoUsage()35}36fun `test mockito usage`() {37val mock = mock<SomeInterface>()38mock.doSomething()39org.mockito.kotlin.Mockito.validateMockitoUsage()40}41fun `test mockito usage`() {42val mock = mock<SomeInterface>()43mock.doSomething()44org.mockito.kotlin.Mockito.validateMockitoUsage()45}46fun `test mockito usage`() {47val mock = mock<SomeInterface>()
validateMockitoUsage
Using AI Code Generation
1val mock = mock<SomeClass>()2validateMockitoUsage()3val mock = mock<SomeClass>()4validateMockitoUsage()5val mock = mock<SomeClass>()6validateMockitoUsage()7val mock = mock<SomeClass>()8validateMockitoUsage()9val mock = mock<SomeClass>()10validateMockitoUsage()11val mock = mock<SomeClass>()12validateMockitoUsage()13val mock = mock<SomeClass>()14validateMockitoUsage()15val mock = mock<SomeClass>()16validateMockitoUsage()17val mock = mock<SomeClass>()18validateMockitoUsage()19val mock = mock<SomeClass>()20validateMockitoUsage()
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!!