mocking-with-mockito
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseMocking with Mockito — The androidx-Native Mocking Stack
使用 Mockito 进行 Mocking——androidx 原生 Mocking 技术栈
Mockito is the mocking framework androidx itself uses — 400+ test files import across the AOSP checkout, while returns zero hits. New Android code that wants to "match what Google does" picks Mockito + the 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.
org.mockitoio.mockkmockito-kotlinMockito 是 androidx 自身使用的 mocking 框架——在 AOSP checkout 中有 400+ 个测试文件导入 ,而 的命中数为零。希望“与 Google 的做法保持一致”的新 Android 代码会选择 Mockito + Kotlin DSL。本 Skill 记录了准确的依赖矩阵、三种 setup 样式、Kotlin DSL API 表面,以及 Kotlin final class 所需的 inline-mock-maker 配置。
org.mockitoio.mockkmockito-kotlinWhen 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 from Mockito 4.x and needs the
Cannot mock/spy class … final classconfiguration.mock-maker-inline - The user reports from mixing raw values with
InvalidUseOfMatchersException/any().eq() - The user is wrestling with the keyword clash in Kotlin (
when) and wants the`when`(mock.foo())DSL.whenever - The user wants with
argumentCaptor<T>()/firstValue/lastValueinstead ofallValues.ArgumentCaptor.forClass(...) - The user is migrating from to
MockitoAnnotations.initMocks(this)or theopenMocks(this)approach.MockitoJUnit.rule() - The user is mocking a class on an instrumented test on API < 28.
final
- 用户正在 Kotlin Android 模块中启动新的测试套件,并询问“应该使用什么 mocking 库”。
- 用户报告 Mockito 4.x 出现 ,需要
Cannot mock/spy class … final class配置。mock-maker-inline - 用户在混用原始值与 /
any()时遇到eq()。InvalidUseOfMatchersException - 用户正在处理 Kotlin 中 关键字冲突(
when),并希望使用`when`(mock.foo())DSL。whenever - 用户希望使用带 /
firstValue/lastValue的allValues,而不是argumentCaptor<T>()。ArgumentCaptor.forClass(...) - 用户正在从 迁移到
MockitoAnnotations.initMocks(this)或openMocks(this)方式。MockitoJUnit.rule() - 用户在 API < 28 的 instrumented test 中 mock 一个 class。
final
When NOT to use this skill
何时不应使用此 Skill
- The user wants /
coEveryfor suspend functions, deep singleton mocking viacoVerify, or static mocking viamockkObject— usemockkStatic.../mocking-with-mockk/SKILL.md - The user is choosing between fakes and mocks at the design level — use . Per /test-doubles, fakes are preferred over mocks for behaviour-heavy collaborators.
../../../fundamentals/doubles/picking-test-doubles/SKILL.md - The runner / Gradle matrix isn't set up yet — start with .
../../runner/configuring-junit4-on-android/SKILL.md - The user wants -aware testing for coroutines — see
runTest.../../coroutines/testing-coroutines-with-runtest/SKILL.md
- 用户需要针对 suspend functions 使用 /
coEvery、通过coVerify进行深层 singleton mocking,或通过mockkObject进行 static mocking——请使用mockkStatic。../mocking-with-mockk/SKILL.md - 用户在设计层面选择 fakes 与 mocks——请使用 。根据 /test-doubles,对于行为密集型协作者,fakes 优于 mocks。
../../../fundamentals/doubles/picking-test-doubles/SKILL.md - runner / Gradle matrix 尚未配置——请先使用 。
../../runner/configuring-junit4-on-android/SKILL.md - 用户希望进行支持 的 coroutine testing——请参阅
runTest。../../coroutines/testing-coroutines-with-runtest/SKILL.md
Prerequisites
前置条件
- The base test wiring from is already in place (
../../runner/configuring-junit4-on-android/SKILL.md,@RunWith(AndroidJUnit4::class), JUnit 4.13.2).androidx.test.ext:junit:1.3.0 - A Kotlin module on JDK 11+ (Mockito 5.x raised the JDK floor to Java 11).
- A is installed if any code-under-test touches
MainDispatcherRule— see the runner skill.Dispatchers.Main
- 来自 的基础测试接线已经就位(
../../runner/configuring-junit4-on-android/SKILL.md、@RunWith(AndroidJUnit4::class)、JUnit 4.13.2)。androidx.test.ext:junit:1.3.0 - Kotlin 模块基于 JDK 11+(Mockito 5.x 将 JDK 最低要求提高到 Java 11)。
- 如果任何被测代码触及 ,则已安装
Dispatchers.Main——请参阅 runner Skill。MainDispatcherRule
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 swap needed for Kotlin final classes:
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-kotlinmockito-core- 2. Pick a mock-lifecycle style. There are three idiomatic options. Prefer the rule for new code; reserve for cases where the test class can't claim
openMocks.@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 returns and leaks inline-mock resources. Always use and close the returned in .
MockitoAnnotations.initMocks(this)voidopenMocks(this)AutoCloseable@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:
-
is reified — no
mock<T>()ceremony.T::class.java -
is a builder block — collapses a chain of
mock { on { … } doReturn … }calls when stubbing at construction time.whenever -
replaces raw Mockito's
whenever(...)(which requires backticks because`when`(...)is a Kotlin keyword).when -
returns a captor with
argumentCaptor<T>()/firstValue/secondValue/lastValueproperties — noallValuesceremony.getValue() -
,
any(),anyOrNull()fromeq()are null-safe in Kotlin (raw Mockito'sorg.mockito.kotlin.*returns Javaany(), which crashes a Kotlin non-nullable parameter).null -
4. Honour the any/eq matcher mixing rule. If ANY argument uses a matcher (,
any(),eq()), ALL arguments must be matchers. Mixing raw values withargThat { … }raisesany(). Wrap raw values inInvalidUseOfMatchersException: 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. Stub suspend functions from any suspend context. Mockito does not have first-class suspend support. The compiler accepts only when the call site is itself suspending.
whenever(mock.suspendFn())already provides that suspend context — wrapping a stub inrunTest { … }insiderunBlocking { … }blocks the test dispatcher and can deadlock underrunTest { … }. Pick one or the other, not both. This is the chief ergonomic friction with Mockito; if the codebase is suspend-heavy, weighMainDispatcherRuleinstead.../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)
}For non-suspending tests (no ), use instead — but never both:
runTestrunBlockingkotlin
@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 containing:
src/test/resources/mockito-extensions/org.mockito.plugins.MockMaker
text
mock-maker-inlineThis is exactly what androidx ships in , , and . The alternative is swapping for in Gradle (which transitively pulls ).
compose/material/material/src/androidHostTest/resources/mockito-extensions/org.mockito.plugins.MockMakercompose/foundation/foundation/.../mockito-extensions/...room3/room3-runtime/.../mockito-extensions/...mockito-coremockito-inlinemockito-coreInline still has limits: private members, /, , and cannot be mocked.
finalequals()hashCode()StringClass- 7. For instrumented tests on API < 28, guard final-class mocks. 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
mockito-androidto the test class with a one-line comment. Real example from@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. Apply 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:
Strictness.STRICT_STUBS
kotlin
@get:Rule val mockitoRule: MockitoRule =
MockitoJUnit.rule().strictness(Strictness.STRICT_STUBS)- 9. Verify the suite runs and produces the expected interactions. . Failed verifications produce the canonical "Wanted but not invoked" / "Argument(s) are different" output — these messages are usually self-diagnosing.
./gradlew :<module>:testDebugUnitTest --tests com.example.UserViewModelTest
- 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-kotlinmockito-core- 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)已弃用的 返回 ,并会泄漏 inline-mock 资源。始终使用 ,并在 中关闭返回的 。
MockitoAnnotations.initMocks(this)voidopenMocks(this)@AfterAutoCloseable- 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))
}
}要点:
-
使用 reified——无需
mock<T>()仪式。T::class.java -
是 builder block——在构造时进行 stub 可将一连串
mock { on { … } doReturn … }调用合并起来。whenever -
取代原始 Mockito 的
whenever(...)(由于`when`(...)是 Kotlin 关键字,后者需要反引号)。when -
返回带有
argumentCaptor<T>()/firstValue/secondValue/lastValue属性的 captor——无需allValues仪式。getValue() -
来自的
org.mockito.kotlin.*、any()、anyOrNull()在 Kotlin 中是 null-safe 的(原始 Mockito 的eq()返回 Javaany(),传入 Kotlin 的 non-nullable 参数时会崩溃)。null -
4. 遵守 any/eq matcher 混用规则。 如果任意参数使用 matcher(、
any()、eq()),则所有参数都必须使用 matcher。将原始值与argThat { … }混用会抛出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())已经提供 suspend context——在runTest { … }内再用runTest { … }包裹 stub 会阻塞 test dispatcher,并可能在runBlocking { … }下死锁。二者择一,不可同时使用。 这是 Mockito 最主要的易用性痛点;如果代码库大量使用 suspend,请权衡是否改用MainDispatcherRule。../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 测试(无 ),请改用 ——但绝不要同时使用两者:
runTestrunBlockingkotlin
@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 在 、 和 中随附的内容。另一种做法是在 Gradle 中将 替换为 (后者会传递引入 )。
compose/material/material/src/androidHostTest/resources/mockito-extensions/org.mockito.plugins.MockMakercompose/foundation/foundation/.../mockito-extensions/...room3/room3-runtime/.../mockito-extensions/...mockito-coremockito-inlinemockito-coreInline 仍有限制:无法 mock private members、/、 和 。
finalequals()hashCode()StringClass- 7. 对于 API < 28 上的 instrumented tests,请限制 final-class mocks。 使用 dexmaker,后者仅支持 API 28+ 上的 final-class mocking。这是 dexmaker 约束,而不是 Mockito 版本约束——升级到 Mockito 5.x 并不会解除该限制;只有 Android API 28 (P) 才引入 dexmaker 所需的 JVMTI hooks。androidx 的惯例是在测试类上添加
mockito-android,并附一行注释。实际示例位于@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. 为新的测试类应用 。 Strict stubs 会将未使用的 stub 和参数不匹配报告为失败,从而捕获那些因为实际上没有执行 stub 而“通过”的测试。通过 rule 进行配置:
Strictness.STRICT_STUBS
kotlin
@get:Rule val mockitoRule: MockitoRule =
MockitoJUnit.rule().strictness(Strictness.STRICT_STUBS)- 9. 验证测试套件能够运行并产生预期交互。 。失败的验证会产生标准的 “Wanted but not invoked” / “Argument(s) are different” 输出——这些消息通常可直接用于诊断问题。
./gradlew :<module>:testDebugUnitTest --tests com.example.UserViewModelTest
Patterns
模式
Pattern: WRONG vs RIGHT — Kotlin when
keyword clash
when模式:错误 vs 正确——Kotlin when
关键字冲突
whenkotlin
// 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.allValueskotlin
// 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.allValuesPattern: 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-inlinekotlin
// 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-inlinekotlin
// 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 AND
org.mockito:mockito-core:5.xfor Kotlin tests. The DSL artifact is non-optional in any modern Kotlin codebase.org.mockito.kotlin:mockito-kotlin:5.x - MUST use from
whenever(...), notorg.mockito.kotlin.*from`when`(...). The keyword-escape form is a code smell.org.mockito.Mockito - MUST use 's
org.mockito.kotlin/any()/anyOrNull()for Kotlin tests. Raw Mockito'seq()returns Javaany()and crashes Kotlin non-nullable parameters at runtime.null - MUST stub suspend functions from a suspending context — either (preferred, integrates with virtual time) or
runTest { whenever(...) doReturn ... }for non-runBlocking { ... }setups. MUST NOT nestrunTestinsiderunBlocking— it blocks the test dispatcher and can deadlock underrunTest. Mockito has no native suspend-stubbing surface; either suspend context is sufficient.MainDispatcherRule - MUST use and close the returned
MockitoAnnotations.openMocks(this)inAutoCloseable. MUST NOT use the deprecated@After.MockitoAnnotations.initMocks(this) - MUST ship with literal contents
mockito-extensions/org.mockito.plugins.MockMakerfor any pre-5.x project that mocks Kotlin final classes. Mockito 5.x ships inline by default and needs nothing.mock-maker-inline - MUST annotate test classes that mock final classes with when they run as
@SdkSuppress(minSdkVersion = 28)againstandroidTestImplementation.mockito-android - MUST keep matchers consistent within a single /
verifycall: all matchers OR no matchers. Wrap raw values inwheneverto mix.eq(...) - 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 and
Mockito.mock(...)in the same file — pick one and be consistent. Prefer the kotlin DSL.org.mockito.kotlin.mock<T>() - PREFERRED: apply to catch dead stubs and argument mismatches. Lenient mode hides bugs.
Strictness.STRICT_STUBS
- 必须同时添加 和
org.mockito:mockito-core:5.x,用于 Kotlin 测试。在任何现代 Kotlin 代码库中,DSL artifact 都是不可省略的。org.mockito.kotlin:mockito-kotlin:5.x - 必须使用 中的
org.mockito.kotlin.*,而不是whenever(...)中的org.mockito.Mockito。转义关键字的形式是一种代码坏味道。`when`(...) - 必须在 Kotlin 测试中使用 的
org.mockito.kotlin/any()/anyOrNull()。原始 Mockito 的eq()返回 Javaany(),运行时会导致 Kotlin non-nullable 参数崩溃。null - 必须从 suspend context 中 stub suspend functions——使用 (推荐,可与 virtual time 集成),或在使用非
runTest { whenever(...) doReturn ... }方案时使用runTest。不得在runBlocking { ... }内嵌套runTest——它会阻塞 test dispatcher,并可能在runBlocking下死锁。Mockito 没有原生的 suspend-stubbing 接口;任意一种 suspend context 均已足够。MainDispatcherRule - 必须使用 ,并在
MockitoAnnotations.openMocks(this)中关闭返回的@After。不得使用已弃用的AutoCloseable。MockitoAnnotations.initMocks(this) - 必须为任何需要 mock Kotlin final class 的 pre-5.x 项目提供 文件,其内容必须为
mockito-extensions/org.mockito.plugins.MockMaker。Mockito 5.x 默认启用 inline,无需此文件。mock-maker-inline - 必须为通过 使用
androidTestImplementation并 mock final class 的测试类添加mockito-android。@SdkSuppress(minSdkVersion = 28) - 必须在单次 /
verify调用中保持 matcher 一致:要么全部使用 matcher,要么全部不使用。需要混用时,将原始值包装在whenever中。eq(...) - 必须对有行为的协作者优先使用 fakes(依据 developer.android.com/training/testing/fundamentals/test-doubles:“fakes ... are preferred”)。使用 Mockito 验证交互,而不是重新实现行为。
- 不得在同一文件中混用 和
Mockito.mock(...)——请选择一种并保持一致。优先使用 Kotlin DSL。org.mockito.kotlin.mock<T>() - **推荐:**应用 ,以捕获失效 stub 和参数不匹配。Lenient 模式会隐藏问题。
Strictness.STRICT_STUBS
Verification
验证
- passes.
./gradlew :<module>:testDebugUnitTest --tests <YourTestClass> - when`" src/test src/androidTest
grep -rn "org.mockito.Mockito.\whenever` instead).returns NO matches (use - returns NO matches (use
grep -rn "MockitoAnnotations.initMocks" src/test src/androidTestinstead).openMocks - returns NO matches in new code (use
grep -rn "ArgumentCaptor.forClass" src/test src/androidTestinstead).argumentCaptor<T>() - If the project is on Mockito 4.x and mocks a Kotlin final class, the file exists with literal contents
src/test/resources/mockito-extensions/org.mockito.plugins.MockMaker.mock-maker-inline - is applied (or the
MockitoJUnit.rule().strictness(Strictness.STRICT_STUBS)JUnit5 annotation).@MockitoSettings(strictness = Strictness.STRICT_STUBS) - No unused stubs reported under .
Strictness.STRICT_STUBS - Final-class instrumented tests carry .
@SdkSuppress(minSdkVersion = 28)
- 通过。
./gradlew :<module>:testDebugUnitTest --tests <YourTestClass> - when`" src/test src/androidTest
grep -rn "org.mockito.Mockito.\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 - 已应用 (或使用 JUnit5 注解
MockitoJUnit.rule().strictness(Strictness.STRICT_STUBS))。@MockitoSettings(strictness = Strictness.STRICT_STUBS) - 下没有报告未使用的 stub。
Strictness.STRICT_STUBS - final-class instrumented tests 带有 。
@SdkSuppress(minSdkVersion = 28)
References
参考资料
- Mockito reference: https://javadoc.io/doc/org.mockito/mockito-core/latest/org/mockito/Mockito.html
- mockito-kotlin: https://github.com/mockito/mockito-kotlin
- Mockito 5 release notes: https://github.com/mockito/mockito/releases/tag/v5.0.0
- Android Developers — Local tests: https://developer.android.com/training/testing/local-tests
- Android Developers — Test doubles: https://developer.android.com/training/testing/fundamentals/test-doubles
- — canonical mockito-kotlin DSL (
androidx/car/app/app/src/test/java/androidx/car/app/serialization/ListDelegateTest.kt,mock<T>(),argumentCaptor<T>(),verify(... atLeastOnce())).lastValue - —
androidx/compose/ui/ui/src/androidHostTest/kotlin/androidx/compose/ui/input/IndirectPointerEventWithInputDeviceMockTest.kt+@RunWith(MockitoJUnitRunner::class)+ raw@SdkSuppress(minSdkVersion = 28)(legacy form).`when` - — literal
androidx/compose/material/material/src/androidHostTest/resources/mockito-extensions/org.mockito.plugins.MockMakercontents.mock-maker-inline - — same plugin file convention.
androidx/compose/foundation/foundation/src/androidHostTest/resources/mockito-extensions/org.mockito.plugins.MockMaker - — same plugin file convention.
androidx/room3/room3-runtime/src/androidHostTest/resources/mockito-extensions/org.mockito.plugins.MockMaker
- Mockito 参考:https://javadoc.io/doc/org.mockito/mockito-core/latest/org/mockito/Mockito.html
- mockito-kotlin:https://github.com/mockito/mockito-kotlin
- Mockito 5 发布说明:https://github.com/mockito/mockito/releases/tag/v5.0.0
- Android Developers — Local tests:https://developer.android.com/training/testing/local-tests
- Android Developers — Test doubles:https://developer.android.com/training/testing/fundamentals/test-doubles
- ——规范的 mockito-kotlin DSL(
androidx/car/app/app/src/test/java/androidx/car/app/serialization/ListDelegateTest.kt、mock<T>()、argumentCaptor<T>()、verify(... atLeastOnce()))。lastValue - ——
androidx/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.MockMaker的插件文件。mock-maker-inline - ——相同的插件文件约定。
androidx/compose/foundation/foundation/src/androidHostTest/resources/mockito-extensions/org.mockito.plugins.MockMaker - ——相同的插件文件约定。
androidx/room3/room3-runtime/src/androidHostTest/resources/mockito-extensions/org.mockito.plugins.MockMaker