我有以下测试类:
@RunWith(MockitoJUnitRunner::class)
class RegistrationDataProviderUnitTest {
private val mMockContext: Context = mock {
on { getString(R.string.is_device_registered_key) } doReturn "is_device_registered_key"
on {
getSharedPreferences(
anyString(), anyInt()
)
} doReturn mMockSharedPreferences
}
private val mMockSharedPreferences: SharedPreferences = mock {
on {
getBoolean(
mMockContext.getString(R.string.is_device_registered_key), false
)
} doReturn true
on {
edit()
} doReturn mMockSharedPreferencesEditor
}
private val mMockSharedPreferencesEditor: SharedPreferences.Editor = mock()
private val okHttpClient: OkHttpClient = mock()
private val analyticsService: AnalyticsService = mock()
private val mRegistrationDataProvider =
RegistrationDataProvider(mMockContext, okHttpClient, analyticsService)
@Test
fun registrationDataProvider_CheckIfDeviceIsRegistered() {
val success: Boolean = mRegistrationDataProvider.checkIfDeviceIsRegistered()
MatcherAssert.assertThat(
"Checking that we retrieved the value of the shared preference key for when device is registered",
success
)
}
}
我在模拟上下文,并在调用 getSharedPreferences 时传递了一个模拟共享首选项。
然后我将上下文传递给我的 RegistrationDataProvider 类。这是该类的外观:
class RegistrationDataProvider @Inject constructor(
@ApplicationContext private val appContext: Context,
private val okHttpClient: OkHttpClient,
private val analyticsService: AnalyticsService
) {
fun checkIfDeviceIsRegistered(): Boolean {
println(appContext)
val sharedPref = appContext.getSharedPreferences(
appContext.getString(R.string.shared_preferences_key),
Context.MODE_PRIVATE
)
println(sharedPref)
return sharedPref.getBoolean(
appContext.getString(R.string.is_device_registered_key),
false
)
}
}
当我调用时,我期望mRegistrationDataProvider.checkIfDeviceIsRegistered()
的是正在使用的共享首选项是 mMockSharedPreferences 的一个实例,但是我得到的只是null。
如您所见,我的checkIfDeviceIsRegistered()
函数中有两个打印语句,其中appContext返回mMockContext,sharedPref返回null。
为什么返回 null 以及如何修改测试以返回正确的值?