Loading...
Loading...
Use this skill to wire Mockito (the dominant Android mocking framework, exclusively used by androidx itself) into a JVM unit-test suite. Covers `org.mockito:mockito-core:5.x` plus the `org.mockito.kotlin:mockito-kotlin:5.x` Kotlin DSL — `mock<T>()`, `whenever`, `argumentCaptor<T>()`, `any()` / `anyOrNull()` / `eq()`, `MockitoJUnit.rule()` vs `MockitoAnnotations.openMocks(this)` lifecycle, the inline mock-maker for Kotlin final classes (`mock-maker-inline` plugin file), `@SdkSuppress(minSdkVersion = 28)` for instrumented final-class mocks, and the suspend-stubbing escape hatch via `runBlocking`. Use when the user mentions `whenever`, `Cannot mock final class`, `InvalidUseOfMatchersException`, `@Mock null`, `MockitoJUnitRunner`, `argumentCaptor`, `mock-maker-inline`, or asks how to mock with mockito-kotlin.
npx skill4agent add skydoves/android-testing-skills mocking-with-mockitoorg.mockitoio.mockkmockito-kotlinCannot mock/spy class … final classmock-maker-inlineInvalidUseOfMatchersExceptionany()eq()when`when`(mock.foo())wheneverargumentCaptor<T>()firstValuelastValueallValuesArgumentCaptor.forClass(...)MockitoAnnotations.initMocks(this)openMocks(this)MockitoJUnit.rule()finalcoEverycoVerifymockkObjectmockkStatic../mocking-with-mockk/SKILL.md../../../fundamentals/doubles/picking-test-doubles/SKILL.md../../runner/configuring-junit4-on-android/SKILL.mdrunTest../../coroutines/testing-coroutines-with-runtest/SKILL.md../../runner/configuring-junit4-on-android/SKILL.md@RunWith(AndroidJUnit4::class)androidx.test.ext:junit:1.3.0MainDispatcherRuleDispatchers.Mainmockito-inlinedependencies {
testImplementation("org.mockito:mockito-core:5.14.2")
testImplementation("org.mockito.kotlin:mockito-kotlin:5.4.0")
// Instrumented final-class mocks (API 28+ only — see step 7)
androidTestImplementation("org.mockito:mockito-android:5.14.2")
androidTestImplementation("org.mockito.kotlin:mockito-kotlin:5.4.0")
}mockito-kotlinmockito-coreopenMocks@RunWith// (a) JUnit4 rule — preferred. No runner ownership, plays nicely with @RunWith(AndroidJUnit4::class).
@get:Rule val mockitoRule: MockitoRule = MockitoJUnit.rule()
// (b) Manual openMocks — works everywhere.
private lateinit var closeable: AutoCloseable
@Before fun setUp() { closeable = MockitoAnnotations.openMocks(this) }
@After fun tearDown() { closeable.close() }
// (c) JUnit5 extension (only if the project is on JUnit 5 via the Vintage engine).
@ExtendWith(MockitoExtension::class)MockitoAnnotations.initMocks(this)voidopenMocks(this)AutoCloseable@Afterorg.mockito.kotlin.*import org.mockito.kotlin.any
import org.mockito.kotlin.argumentCaptor
import org.mockito.kotlin.atLeastOnce
import org.mockito.kotlin.doReturn
import org.mockito.kotlin.eq
import org.mockito.kotlin.mock
import org.mockito.kotlin.verify
import org.mockito.kotlin.whenever
class UserViewModelTest {
@get:Rule val mockitoRule = MockitoJUnit.rule()
@get:Rule val mainDispatcherRule = MainDispatcherRule()
private val repo: UserRepository = mock()
private val analytics: Analytics = mock {
on { isEnabled() } doReturn true
}
@Test fun loadsUserAndLogs() = runTest {
whenever(repo.findById(7L)) doReturn User("Jane")
val vm = UserViewModel(repo, analytics)
vm.load(7L)
advanceUntilIdle()
val captor = argumentCaptor<AnalyticsEvent>()
verify(analytics, atLeastOnce()).log(captor.capture())
assertThat(captor.lastValue.name).isEqualTo("user_loaded")
verify(repo).findById(eq(7L))
}
}mock<T>()T::class.javamock { on { … } doReturn … }wheneverwhenever(...)`when`(...)whenargumentCaptor<T>()firstValuesecondValuelastValueallValuesgetValue()any()anyOrNull()eq()org.mockito.kotlin.*any()nullany()eq()argThat { … }any()InvalidUseOfMatchersException: Misplaced or misused argument matchereq(...)verify(repo).save(any(), eq("identifier")) // RIGHT — all args are matchers
verify(repo).save(any(), "identifier") // WRONG — InvalidUseOfMatchersExceptionwhenever(mock.suspendFn())runTest { … }runBlocking { … }runTest { … }MainDispatcherRule../mocking-with-mockk/SKILL.md@Test fun loadsUser() = runTest {
whenever(repo.fetchUser(1)) doReturn User("Jane") // RIGHT — runTest IS a suspend context
val vm = UserViewModel(repo)
vm.load(1)
advanceUntilIdle()
verify(repo).fetchUser(1)
}runTestrunBlocking@Test fun loadsUser() = runBlocking {
whenever(repo.fetchUser(1)) doReturn User("Jane")
val result = UserService(repo).get(1)
assertThat(result.name).isEqualTo("Jane")
}src/test/resources/mockito-extensions/org.mockito.plugins.MockMakermock-maker-inlinecompose/material/material/src/androidHostTest/resources/mockito-extensions/org.mockito.plugins.MockMakercompose/foundation/foundation/.../mockito-extensions/...room3/room3-runtime/.../mockito-extensions/...mockito-coremockito-inlinemockito-corefinalequals()hashCode()StringClassmockito-android@SdkSuppress(minSdkVersion = 28)compose/ui/ui/src/androidHostTest/kotlin/androidx/compose/ui/input/IndirectPointerEventWithInputDeviceMockTest.ktimport androidx.test.filters.SdkSuppress
@RunWith(MockitoJUnitRunner::class)
@SdkSuppress(minSdkVersion = 28) // Mocks for final classes can only be done on 28 and higher
class IndirectPointerEventWithInputDeviceMockTest { /* ... */ }Strictness.STRICT_STUBS@get:Rule val mockitoRule: MockitoRule =
MockitoJUnit.rule().strictness(Strictness.STRICT_STUBS)./gradlew :<module>:testDebugUnitTest --tests com.example.UserViewModelTestwhen// WRONG — raw Mockito from Kotlin
import org.mockito.Mockito.`when`
`when`(repo.fetch()).thenReturn(User("Jane"))
// WRONG because: `when` requires backtick-escaping in Kotlin (it is a reserved keyword),
// the import line is awkward, and any() returns Java null which crashes Kotlin
// non-nullable parameters. mockito-kotlin's whenever / null-safe matchers solve both.// RIGHT — mockito-kotlin DSL
import org.mockito.kotlin.whenever
import org.mockito.kotlin.doReturn
whenever(repo.fetch()) doReturn User("Jane")// WRONG
import org.mockito.ArgumentCaptor
val captor = ArgumentCaptor.forClass(User::class.java)
verify(repo).save(captor.capture())
assertEquals("Jane", captor.value.name)
// WRONG because: ArgumentCaptor.forClass requires .java, captor.value collides with
// Kotlin's value class semantics for some types, and there's no firstValue/lastValue
// accessor for sequences of captures.// RIGHT
import org.mockito.kotlin.argumentCaptor
val captor = argumentCaptor<User>()
verify(repo, atLeastOnce()).save(captor.capture())
assertEquals("Jane", captor.lastValue.name)
val all: List<User> = captor.allValues// WRONG — Mockito 4.x without the inline plugin, mocking a Kotlin final class
val service: PaymentService = mock()
// WRONG because: Kotlin classes are final by default. The classic subclass mock-maker
// throws "Cannot mock/spy class com.example.PaymentService — final class". Either
// upgrade to Mockito 5.x (inline by default) or install the plugin file.// RIGHT — src/test/resources/mockito-extensions/org.mockito.plugins.MockMaker
mock-maker-inline// Mockito 5.x: nothing else to do; mock<PaymentService>() works out of the box.// WRONG — silent passing test
class MyTest {
@get:Rule val mockitoRule = MockitoJUnit.rule() // default lenient
@Test fun loadsUser() {
whenever(repo.findById(7L)) doReturn User("Jane")
val vm = UserViewModel(repo)
vm.load(8L) // wrong id — stub is never used
verify(repo).findById(any()) // passes because findById was called
}
}
// WRONG because: the test claims to verify behaviour for id=7 but actually exercises id=8.
// The stub is dead. STRICT_STUBS catches this with PotentialStubbingProblem.// RIGHT
@get:Rule val mockitoRule: MockitoRule =
MockitoJUnit.rule().strictness(Strictness.STRICT_STUBS)
// Now PotentialStubbingProblem fires at runtime if the stub argument doesn't match
// what the SUT actually calls.org.mockito:mockito-core:5.xorg.mockito.kotlin:mockito-kotlin:5.xwhenever(...)org.mockito.kotlin.*`when`(...)org.mockito.Mockitoorg.mockito.kotlinany()anyOrNull()eq()any()nullrunTest { whenever(...) doReturn ... }runBlocking { ... }runTestrunBlockingrunTestMainDispatcherRuleMockitoAnnotations.openMocks(this)AutoCloseable@AfterMockitoAnnotations.initMocks(this)mockito-extensions/org.mockito.plugins.MockMakermock-maker-inline@SdkSuppress(minSdkVersion = 28)androidTestImplementationmockito-androidverifywhenevereq(...)Mockito.mock(...)org.mockito.kotlin.mock<T>()Strictness.STRICT_STUBS./gradlew :<module>:testDebugUnitTest --tests <YourTestClass>grep -rn "org.mockito.Mockito.\returns NO matches (usegrep -rn "MockitoAnnotations.initMocks" src/test src/androidTestopenMocksgrep -rn "ArgumentCaptor.forClass" src/test src/androidTestargumentCaptor<T>()src/test/resources/mockito-extensions/org.mockito.plugins.MockMakermock-maker-inlineMockitoJUnit.rule().strictness(Strictness.STRICT_STUBS)@MockitoSettings(strictness = Strictness.STRICT_STUBS)Strictness.STRICT_STUBS@SdkSuppress(minSdkVersion = 28)androidx/car/app/app/src/test/java/androidx/car/app/serialization/ListDelegateTest.ktmock<T>()argumentCaptor<T>()verify(... atLeastOnce())lastValueandroidx/compose/ui/ui/src/androidHostTest/kotlin/androidx/compose/ui/input/IndirectPointerEventWithInputDeviceMockTest.kt@RunWith(MockitoJUnitRunner::class)@SdkSuppress(minSdkVersion = 28)`when`androidx/compose/material/material/src/androidHostTest/resources/mockito-extensions/org.mockito.plugins.MockMakermock-maker-inlineandroidx/compose/foundation/foundation/src/androidHostTest/resources/mockito-extensions/org.mockito.plugins.MockMakerandroidx/room3/room3-runtime/src/androidHostTest/resources/mockito-extensions/org.mockito.plugins.MockMaker