mocking-with-mockito

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Mocking with Mockito — The androidx-Native Mocking Stack

使用 Mockito 进行 Mocking——androidx 原生 Mocking 技术栈

Mockito is the mocking framework androidx itself uses — 400+ test files import
org.mockito
across the AOSP checkout, while
io.mockk
returns zero hits. New Android code that wants to "match what Google does" picks Mockito + the
mockito-kotlin
Kotlin DSL. This skill documents the exact dependency matrix, the three setup styles, the Kotlin DSL surface, and the inline-mock-maker plumbing required for Kotlin final classes.
Mockito 是 androidx 自身使用的 mocking 框架——在 AOSP checkout 中有 400+ 个测试文件导入
org.mockito
,而
io.mockk
的命中数为零。希望“与 Google 的做法保持一致”的新 Android 代码会选择 Mockito +
mockito-kotlin
Kotlin DSL。本 Skill 记录了准确的依赖矩阵、三种 setup 样式、Kotlin DSL API 表面,以及 Kotlin final class 所需的 inline-mock-maker 配置。

When to use this skill

何时使用此 Skill

  • The user is starting a new test suite in a Kotlin Android module and asks "what mocking library should I use".
  • The user reports
    Cannot mock/spy class … final class
    from Mockito 4.x and needs the
    mock-maker-inline
    configuration.
  • The user reports
    InvalidUseOfMatchersException
    from mixing raw values with
    any()
    /
    eq()
    .
  • The user is wrestling with the
    when
    keyword clash in Kotlin (
    `when`(mock.foo())
    ) and wants the
    whenever
    DSL.
  • The user wants
    argumentCaptor<T>()
    with
    firstValue
    /
    lastValue
    /
    allValues
    instead of
    ArgumentCaptor.forClass(...)
    .
  • The user is migrating from
    MockitoAnnotations.initMocks(this)
    to
    openMocks(this)
    or the
    MockitoJUnit.rule()
    approach.
  • The user is mocking a
    final
    class on an instrumented test on API < 28.
  • 用户正在 Kotlin Android 模块中启动新的测试套件,并询问“应该使用什么 mocking 库”。
  • 用户报告 Mockito 4.x 出现
    Cannot mock/spy class … final class
    ,需要
    mock-maker-inline
    配置。
  • 用户在混用原始值与
    any()
    /
    eq()
    时遇到
    InvalidUseOfMatchersException
    。
  • 用户正在处理 Kotlin 中
    when
    关键字冲突(
    `when`(mock.foo())
    ),并希望使用
    whenever
    DSL。
  • 用户希望使用带
    firstValue
    /
    lastValue
    /
    allValues
    的
    argumentCaptor<T>()
    ,而不是
    ArgumentCaptor.forClass(...)
    。
  • 用户正在从
    MockitoAnnotations.initMocks(this)
    迁移到
    openMocks(this)
    或
    MockitoJUnit.rule()
    方式。
  • 用户在 API < 28 的 instrumented test 中 mock 一个
    final
    class。

When NOT to use this skill

何时不应使用此 Skill

  • The user wants
    coEvery
    /
    coVerify
    for suspend functions, deep singleton mocking via
    mockkObject
    , or static mocking via
    mockkStatic
    — use
    ../mocking-with-mockk/SKILL.md
    .
  • The user is choosing between fakes and mocks at the design level — use
    ../../../fundamentals/doubles/picking-test-doubles/SKILL.md
    . Per /test-doubles, fakes are preferred over mocks for behaviour-heavy collaborators.
  • The runner / Gradle matrix isn't set up yet — start with
    ../../runner/configuring-junit4-on-android/SKILL.md
    .
  • The user wants
    runTest
    -aware testing for coroutines — see
    ../../coroutines/testing-coroutines-with-runtest/SKILL.md
    .
  • 用户需要针对 suspend functions 使用
    coEvery
    /
    coVerify
    、通过
    mockkObject
    进行深层 singleton mocking,或通过
    mockkStatic
    进行 static mocking——请使用
    ../mocking-with-mockk/SKILL.md
    。
  • 用户在设计层面选择 fakes 与 mocks——请使用
    ../../../fundamentals/doubles/picking-test-doubles/SKILL.md
    。根据 /test-doubles,对于行为密集型协作者,fakes 优于 mocks。
  • runner / Gradle matrix 尚未配置——请先使用
    ../../runner/configuring-junit4-on-android/SKILL.md
    。
  • 用户希望进行支持
    runTest
    的 coroutine testing——请参阅
    ../../coroutines/testing-coroutines-with-runtest/SKILL.md
    。

Prerequisites

前置条件

  • The base test wiring from
    ../../runner/configuring-junit4-on-android/SKILL.md
    is already in place (
    @RunWith(AndroidJUnit4::class)
    ,
    androidx.test.ext:junit:1.3.0
    , JUnit 4.13.2).
  • A Kotlin module on JDK 11+ (Mockito 5.x raised the JDK floor to Java 11).
  • A
    MainDispatcherRule
    is installed if any code-under-test touches
    Dispatchers.Main
    — see the runner skill.
  • 来自
    ../../runner/configuring-junit4-on-android/SKILL.md
    的基础测试接线已经就位(
    @RunWith(AndroidJUnit4::class)
    、
    androidx.test.ext:junit:1.3.0
    、JUnit 4.13.2)。
  • Kotlin 模块基于 JDK 11+(Mockito 5.x 将 JDK 最低要求提高到 Java 11)。
  • 如果任何被测代码触及
    Dispatchers.Main
    ,则已安装
    MainDispatcherRule
    ——请参阅 runner Skill。

Workflow

工作流

  • 1. Add the Mockito + mockito-kotlin coordinates. Mockito 5.x is the recommended baseline because the inline mock-maker is enabled by default — no plugin file or
    mockito-inline
    swap needed for Kotlin final classes:
kotlin
dependencies {
    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-kotlin
is NOT a fork — it is a thin DSL helper layer that delegates straight to
mockito-core
. Both must be on the classpath.
  • 2. Pick a mock-lifecycle style. There are three idiomatic options. Prefer the rule for new code; reserve
    openMocks
    for cases where the test class can't claim
    @RunWith
    .
kotlin
// (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)
The deprecated
MockitoAnnotations.initMocks(this)
returns
void
and leaks inline-mock resources. Always use
openMocks(this)
and close the returned
AutoCloseable
in
@After
.
  • 3. Declare mocks and stub them with the mockito-kotlin DSL. The Kotlin-friendly entry points live under
    org.mockito.kotlin.*
    :
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))
    }
}
Highlights:
  • mock<T>()
    is reified — no
    T::class.java
    ceremony.
  • mock { on { … } doReturn … }
    is a builder block — collapses a chain of
    whenever
    calls when stubbing at construction time.
  • whenever(...)
    replaces raw Mockito's
    `when`(...)
    (which requires backticks because
    when
    is a Kotlin keyword).
  • argumentCaptor<T>()
    returns a captor with
    firstValue
    /
    secondValue
    /
    lastValue
    /
    allValues
    properties — no
    getValue()
    ceremony.
  • any()
    ,
    anyOrNull()
    ,
    eq()
    from
    org.mockito.kotlin.*
    are null-safe in Kotlin (raw Mockito's
    any()
    returns Java
    null
    , which crashes a Kotlin non-nullable parameter).
  • 4. Honour the any/eq matcher mixing rule. If ANY argument uses a matcher (
    any()
    ,
    eq()
    ,
    argThat { … }
    ), ALL arguments must be matchers. Mixing raw values with
    any()
    raises
    InvalidUseOfMatchersException: Misplaced or misused argument matcher
    . Wrap raw values in
    eq(...)
    :
kotlin
verify(repo).save(any(), eq("identifier"))   // RIGHT — all args are matchers
verify(repo).save(any(), "identifier")        // WRONG — InvalidUseOfMatchersException
  • 5. Stub suspend functions from any suspend context. Mockito does not have first-class suspend support. The compiler accepts
    whenever(mock.suspendFn())
    only when the call site is itself suspending.
    runTest { … }
    already provides that suspend context — wrapping a stub in
    runBlocking { … }
    inside
    runTest { … }
    blocks the test dispatcher and can deadlock under
    MainDispatcherRule
    . Pick one or the other, not both.
    This is the chief ergonomic friction with Mockito; if the codebase is suspend-heavy, weigh
    ../mocking-with-mockk/SKILL.md
    instead.
kotlin
@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)
}
For non-suspending tests (no
runTest
), use
runBlocking
instead — but never both:
kotlin
@Test fun loadsUser() = runBlocking {
    whenever(repo.fetchUser(1)) doReturn User("Jane")
    val result = UserService(repo).get(1)
    assertThat(result.name).isEqualTo("Jane")
}
  • 6. For Mockito 4.x, install the inline mock-maker via the resource file. Mockito 5.x already enables it by default. For older versions, drop a single-line file at
    src/test/resources/mockito-extensions/org.mockito.plugins.MockMaker
    containing:
text
mock-maker-inline
This is exactly what androidx ships in
compose/material/material/src/androidHostTest/resources/mockito-extensions/org.mockito.plugins.MockMaker
,
compose/foundation/foundation/.../mockito-extensions/...
, and
room3/room3-runtime/.../mockito-extensions/...
. The alternative is swapping
mockito-core
for
mockito-inline
in Gradle (which transitively pulls
mockito-core
).
Inline still has limits:
final
private members,
equals()
/
hashCode()
,
String
, and
Class
cannot be mocked.
  • 7. For instrumented tests on API < 28, guard final-class mocks.
    mockito-android
    uses dexmaker, which only supports final-class mocking on API 28+. This is a dexmaker constraint, not a Mockito version constraint — upgrading to Mockito 5.x does not lift it; only Android API 28 (P) introduced the JVMTI hooks dexmaker needs. The androidx convention is to add
    @SdkSuppress(minSdkVersion = 28)
    to the test class with a one-line comment. Real example from
    compose/ui/ui/src/androidHostTest/kotlin/androidx/compose/ui/input/IndirectPointerEventWithInputDeviceMockTest.kt
    :
kotlin
import androidx.test.filters.SdkSuppress

@RunWith(MockitoJUnitRunner::class)
@SdkSuppress(minSdkVersion = 28)   // Mocks for final classes can only be done on 28 and higher
class IndirectPointerEventWithInputDeviceMockTest { /* ... */ }
  • 8. Apply
    Strictness.STRICT_STUBS
    for new test classes.
    Strict stubs surface unused stubs and argument mismatches as failures, catching tests that "pass" because they don't actually exercise the stub. Wire it via the rule:
kotlin
@get:Rule val mockitoRule: MockitoRule =
    MockitoJUnit.rule().strictness(Strictness.STRICT_STUBS)
  • 9. Verify the suite runs and produces the expected interactions.
    ./gradlew :<module>:testDebugUnitTest --tests com.example.UserViewModelTest
    . Failed verifications produce the canonical "Wanted but not invoked" / "Argument(s) are different" output — these messages are usually self-diagnosing.
  • 1. 添加 Mockito + mockito-kotlin 坐标。 Mockito 5.x 是推荐基线,因为 inline mock-maker 默认启用——对于 Kotlin final class,无需插件文件,也无需切换到
    mockito-inline
    :
kotlin
dependencies {
    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-kotlin
不是 fork——它是一个轻量 DSL helper layer,直接委托给
mockito-core
。两者都必须位于 classpath 上。
  • 2. 选择 mock-lifecycle 样式。 有三种惯用方案。对于新代码优先使用 rule;仅当测试类无法声明
    @RunWith
    时才使用
    openMocks
    。
kotlin
// (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)
返回
void
,并会泄漏 inline-mock 资源。始终使用
openMocks(this)
,并在
@After
中关闭返回的
AutoCloseable
。
  • 3. 声明 mocks,并使用 mockito-kotlin DSL 对其进行 stub。 Kotlin 友好的入口位于
    org.mockito.kotlin.*
    :
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>()
    使用 reified——无需
    T::class.java
    仪式。
  • mock { on { … } doReturn … }
    是 builder block——在构造时进行 stub 可将一连串
    whenever
    调用合并起来。
  • whenever(...)
    取代原始 Mockito 的
    `when`(...)
    (由于
    when
    是 Kotlin 关键字,后者需要反引号)。
  • argumentCaptor<T>()
    返回带有
    firstValue
    /
    secondValue
    /
    lastValue
    /
    allValues
    属性的 captor——无需
    getValue()
    仪式。
  • 来自
    org.mockito.kotlin.*
    的
    any()
    、
    anyOrNull()
    、
    eq()
    在 Kotlin 中是 null-safe 的(原始 Mockito 的
    any()
    返回 Java
    null
    ,传入 Kotlin 的 non-nullable 参数时会崩溃)。
  • 4. 遵守 any/eq matcher 混用规则。 如果任意参数使用 matcher(
    any()
    、
    eq()
    、
    argThat { … }
    ),则所有参数都必须使用 matcher。将原始值与
    any()
    混用会抛出
    InvalidUseOfMatchersException: Misplaced or misused argument matcher
    。将原始值包装在
    eq(...)
    中:
kotlin
verify(repo).save(any(), eq("identifier"))   // RIGHT — all args are matchers
verify(repo).save(any(), "identifier")        // WRONG — InvalidUseOfMatchersException
  • 5. 从任意 suspend context 中 stub suspend functions。 Mockito 不提供 first-class suspend support。仅当调用点本身是 suspending 时,compiler 才会接受
    whenever(mock.suspendFn())
    。
    runTest { … }
    已经提供 suspend context——在
    runTest { … }
    内再用
    runBlocking { … }
    包裹 stub 会阻塞 test dispatcher,并可能在
    MainDispatcherRule
    下死锁。二者择一,不可同时使用。
    这是 Mockito 最主要的易用性痛点;如果代码库大量使用 suspend,请权衡是否改用
    ../mocking-with-mockk/SKILL.md
    。
kotlin
@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)
}
对于非 suspending 测试(无
runTest
),请改用
runBlocking
——但绝不要同时使用两者:
kotlin
@Test fun loadsUser() = runBlocking {
    whenever(repo.fetchUser(1)) doReturn User("Jane")
    val result = UserService(repo).get(1)
    assertThat(result.name).isEqualTo("Jane")
}
  • 6. 对于 Mockito 4.x,通过 resource file 安装 inline mock-maker。 Mockito 5.x 已默认启用。对于旧版本,在
    src/test/resources/mockito-extensions/org.mockito.plugins.MockMaker
    放置一个包含以下单行内容的文件:
text
mock-maker-inline
这正是 androidx 在
compose/material/material/src/androidHostTest/resources/mockito-extensions/org.mockito.plugins.MockMaker
、
compose/foundation/foundation/.../mockito-extensions/...
和
room3/room3-runtime/.../mockito-extensions/...
中随附的内容。另一种做法是在 Gradle 中将
mockito-core
替换为
mockito-inline
(后者会传递引入
mockito-core
)。
Inline 仍有限制:无法 mock
final
private members、
equals()
/
hashCode()
、
String
和
Class
。
  • 7. 对于 API < 28 上的 instrumented tests,请限制 final-class mocks。
    mockito-android
    使用 dexmaker,后者仅支持 API 28+ 上的 final-class mocking。这是 dexmaker 约束,而不是 Mockito 版本约束——升级到 Mockito 5.x 并不会解除该限制;只有 Android API 28 (P) 才引入 dexmaker 所需的 JVMTI hooks。androidx 的惯例是在测试类上添加
    @SdkSuppress(minSdkVersion = 28)
    ,并附一行注释。实际示例位于
    compose/ui/ui/src/androidHostTest/kotlin/androidx/compose/ui/input/IndirectPointerEventWithInputDeviceMockTest.kt
    :
kotlin
import androidx.test.filters.SdkSuppress

@RunWith(MockitoJUnitRunner::class)
@SdkSuppress(minSdkVersion = 28)   // Mocks for final classes can only be done on 28 and higher
class IndirectPointerEventWithInputDeviceMockTest { /* ... */ }
  • 8. 为新的测试类应用
    Strictness.STRICT_STUBS
    。
    Strict stubs 会将未使用的 stub 和参数不匹配报告为失败,从而捕获那些因为实际上没有执行 stub 而“通过”的测试。通过 rule 进行配置:
kotlin
@get:Rule val mockitoRule: MockitoRule =
    MockitoJUnit.rule().strictness(Strictness.STRICT_STUBS)
  • 9. 验证测试套件能够运行并产生预期交互。
    ./gradlew :<module>:testDebugUnitTest --tests com.example.UserViewModelTest
    。失败的验证会产生标准的 “Wanted but not invoked” / “Argument(s) are different” 输出——这些消息通常可直接用于诊断问题。

Patterns

模式

Pattern: WRONG vs RIGHT — Kotlin
when
keyword clash

模式:错误 vs 正确——Kotlin
when
关键字冲突

kotlin
// 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.
kotlin
// RIGHT — mockito-kotlin DSL
import org.mockito.kotlin.whenever
import org.mockito.kotlin.doReturn

whenever(repo.fetch()) doReturn User("Jane")
kotlin
// 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.
kotlin
// RIGHT — mockito-kotlin DSL
import org.mockito.kotlin.whenever
import org.mockito.kotlin.doReturn

whenever(repo.fetch()) doReturn User("Jane")

Pattern: WRONG vs RIGHT — argument captor verbosity

模式:错误 vs 正确——argument captor 冗长写法

kotlin
// 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.
kotlin
// 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
kotlin
// 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.
kotlin
// 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

Pattern: WRONG vs RIGHT — final-class mocking on Mockito 4.x

模式:错误 vs 正确——在 Mockito 4.x 上 mock final class

kotlin
// 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.
text
// RIGHT — src/test/resources/mockito-extensions/org.mockito.plugins.MockMaker
mock-maker-inline
kotlin
// Mockito 5.x: nothing else to do; mock<PaymentService>() works out of the box.
kotlin
// 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.
text
// RIGHT — src/test/resources/mockito-extensions/org.mockito.plugins.MockMaker
mock-maker-inline
kotlin
// Mockito 5.x: nothing else to do; mock<PaymentService>() works out of the box.

Pattern: WRONG vs RIGHT — strict stubs catch the dead stub

模式:错误 vs 正确——strict stubs 捕获失效 stub

kotlin
// 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.
kotlin
// 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.
kotlin
// 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.
kotlin
// 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.

Mandatory rules

强制规则

  • MUST add both
    org.mockito:mockito-core:5.x
    AND
    org.mockito.kotlin:mockito-kotlin:5.x
    for Kotlin tests. The DSL artifact is non-optional in any modern Kotlin codebase.
  • MUST use
    whenever(...)
    from
    org.mockito.kotlin.*
    , not
    `when`(...)
    from
    org.mockito.Mockito
    . The keyword-escape form is a code smell.
  • MUST use
    org.mockito.kotlin
    's
    any()
    /
    anyOrNull()
    /
    eq()
    for Kotlin tests. Raw Mockito's
    any()
    returns Java
    null
    and crashes Kotlin non-nullable parameters at runtime.
  • MUST stub suspend functions from a suspending context — either
    runTest { whenever(...) doReturn ... }
    (preferred, integrates with virtual time) or
    runBlocking { ... }
    for non-
    runTest
    setups. MUST NOT nest
    runBlocking
    inside
    runTest
    — it blocks the test dispatcher and can deadlock under
    MainDispatcherRule
    . Mockito has no native suspend-stubbing surface; either suspend context is sufficient.
  • MUST use
    MockitoAnnotations.openMocks(this)
    and close the returned
    AutoCloseable
    in
    @After
    . MUST NOT use the deprecated
    MockitoAnnotations.initMocks(this)
    .
  • MUST ship
    mockito-extensions/org.mockito.plugins.MockMaker
    with literal contents
    mock-maker-inline
    for any pre-5.x project that mocks Kotlin final classes. Mockito 5.x ships inline by default and needs nothing.
  • MUST annotate test classes that mock final classes with
    @SdkSuppress(minSdkVersion = 28)
    when they run as
    androidTestImplementation
    against
    mockito-android
    .
  • MUST keep matchers consistent within a single
    verify
    /
    whenever
    call: all matchers OR no matchers. Wrap raw values in
    eq(...)
    to mix.
  • MUST prefer fakes over mocks for collaborators with behaviour (per developer.android.com/training/testing/fundamentals/test-doubles: "fakes ... are preferred"). Use Mockito for verifying interactions, not for re-implementing behaviour.
  • MUST NOT mix
    Mockito.mock(...)
    and
    org.mockito.kotlin.mock<T>()
    in the same file — pick one and be consistent. Prefer the kotlin DSL.
  • PREFERRED: apply
    Strictness.STRICT_STUBS
    to catch dead stubs and argument mismatches. Lenient mode hides bugs.
  • 必须同时添加
    org.mockito:mockito-core:5.x
    和
    org.mockito.kotlin:mockito-kotlin:5.x
    ,用于 Kotlin 测试。在任何现代 Kotlin 代码库中,DSL artifact 都是不可省略的。
  • 必须使用
    org.mockito.kotlin.*
    中的
    whenever(...)
    ,而不是
    org.mockito.Mockito
    中的
    `when`(...)
    。转义关键字的形式是一种代码坏味道。
  • 必须在 Kotlin 测试中使用
    org.mockito.kotlin
    的
    any()
    /
    anyOrNull()
    /
    eq()
    。原始 Mockito 的
    any()
    返回 Java
    null
    ,运行时会导致 Kotlin non-nullable 参数崩溃。
  • 必须从 suspend context 中 stub suspend functions——使用
    runTest { whenever(...) doReturn ... }
    (推荐,可与 virtual time 集成),或在使用非
    runTest
    方案时使用
    runBlocking { ... }
    。不得在
    runTest
    内嵌套
    runBlocking
    ——它会阻塞 test dispatcher,并可能在
    MainDispatcherRule
    下死锁。Mockito 没有原生的 suspend-stubbing 接口;任意一种 suspend context 均已足够。
  • 必须使用
    MockitoAnnotations.openMocks(this)
    ,并在
    @After
    中关闭返回的
    AutoCloseable
    。不得使用已弃用的
    MockitoAnnotations.initMocks(this)
    。
  • 必须为任何需要 mock Kotlin final class 的 pre-5.x 项目提供
    mockito-extensions/org.mockito.plugins.MockMaker
    文件,其内容必须为
    mock-maker-inline
    。Mockito 5.x 默认启用 inline,无需此文件。
  • 必须为通过
    androidTestImplementation
    使用
    mockito-android
    并 mock final class 的测试类添加
    @SdkSuppress(minSdkVersion = 28)
    。
  • 必须在单次
    verify
    /
    whenever
    调用中保持 matcher 一致:要么全部使用 matcher,要么全部不使用。需要混用时,将原始值包装在
    eq(...)
    中。
  • 必须对有行为的协作者优先使用 fakes(依据 developer.android.com/training/testing/fundamentals/test-doubles:“fakes ... are preferred”)。使用 Mockito 验证交互,而不是重新实现行为。
  • 不得在同一文件中混用
    Mockito.mock(...)
    和
    org.mockito.kotlin.mock<T>()
    ——请选择一种并保持一致。优先使用 Kotlin DSL。
  • **推荐:**应用
    Strictness.STRICT_STUBS
    ,以捕获失效 stub 和参数不匹配。Lenient 模式会隐藏问题。

Verification

验证

  • ./gradlew :<module>:testDebugUnitTest --tests <YourTestClass>
    passes.
  • grep -rn "org.mockito.Mockito.\
    when`" src/test src/androidTest
    returns NO matches (use
    whenever` instead).
  • grep -rn "MockitoAnnotations.initMocks" src/test src/androidTest
    returns NO matches (use
    openMocks
    instead).
  • grep -rn "ArgumentCaptor.forClass" src/test src/androidTest
    returns NO matches in new code (use
    argumentCaptor<T>()
    instead).
  • If the project is on Mockito 4.x and mocks a Kotlin final class, the file
    src/test/resources/mockito-extensions/org.mockito.plugins.MockMaker
    exists with literal contents
    mock-maker-inline
    .
  • MockitoJUnit.rule().strictness(Strictness.STRICT_STUBS)
    is applied (or the
    @MockitoSettings(strictness = Strictness.STRICT_STUBS)
    JUnit5 annotation).
  • No unused stubs reported under
    Strictness.STRICT_STUBS
    .
  • Final-class instrumented tests carry
    @SdkSuppress(minSdkVersion = 28)
    .
  • ./gradlew :<module>:testDebugUnitTest --tests <YourTestClass>
    通过。
  • grep -rn "org.mockito.Mockito.\
    when`" src/test src/androidTest
    没有匹配结果(改用
    whenever`)。
  • grep -rn "MockitoAnnotations.initMocks" src/test src/androidTest
    没有匹配结果(改用
    openMocks
    )。
  • grep -rn "ArgumentCaptor.forClass" src/test src/androidTest
    在新代码中没有匹配结果(改用
    argumentCaptor<T>()
    )。
  • 如果项目使用 Mockito 4.x 并 mock Kotlin final class,则文件
    src/test/resources/mockito-extensions/org.mockito.plugins.MockMaker
    存在,且内容为
    mock-maker-inline
    。
  • 已应用
    MockitoJUnit.rule().strictness(Strictness.STRICT_STUBS)
    (或使用 JUnit5 注解
    @MockitoSettings(strictness = Strictness.STRICT_STUBS)
    )。
  • Strictness.STRICT_STUBS
    下没有报告未使用的 stub。
  • final-class instrumented tests 带有
    @SdkSuppress(minSdkVersion = 28)
    。

References

参考资料