【发布时间】:2026-01-11 18:45:01
【问题描述】:
我正在为 sharedpreferences 编写一个 JUnit 测试用例,如下所示
class SharedPrefTest {
private lateinit var context: Context
private lateinit var userRepo: UserRepo
private lateinit var sharedPreferences: SharedPreferences
@Before
fun setup() {
context = mock()
userRepo = UserRepo(context)
}
@Test
fun `check mocked instances are not null`() {
context assertNotEquals null //mocked successfully
userRepo assertNotEquals null
} //PASS
@Test
fun `when shared pref instance not null then do further ops`() {
sharedPreferences = context.getSharedPreferences(USER_PREFS, Context.MODE_PRIVATE)
sharedPreferences assertNotEquals null
} //FAIL
companion object {
const val USER_PREFS = "userprefs"
}
}
但是,我遇到了错误。
context.getSharedPreferences(USER_PREFS, Context.MODE_PRIVATE) must not be null
java.lang.NullPointerException: context.getSharedPreferences(USER_PREFS, Context.MODE_PRIVATE) must not be null
我已经在单独的单元测试用例中检查了 context is not null 但仍然失败。
【问题讨论】:
-
我不明白这个问题!您已经模拟了上下文。为什么它会向 getSharedPreferences 返回非存根(非空)响应?
-
使用Robolectric 编写单元测试。您无需手动模拟 Context 等 Android 框架依赖项。
-
@ashu 问题在于它没有创建 sharedpreference 的实例并抛出 null 错误。此外,仅限使用 Mockito
标签: android kotlin junit mockito sharedpreferences