如何解决共享偏好的 Mockito 单元测试
我正在尝试对几个简单的方法进行简单的单元测试,但这是我第一次尝试使用 mockito,所以我真的不明白我做错了什么。
这是我要测试的课程
object AppPreferenceHelper {
private var sharedPreferences: SharedPreferences? = null
fun initPreferences(context: Context) {
sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context)
}
fun checkIsFavorite(id: String): Boolean {
getFavorites()
favorites?.forEach {
if (it == id)
return true
}
return false
}
fun addFavorite(id: String?) {
id?.let {
favorites?.add(it)
val gson = Gson()
val temp = gson.toJson(favorites)
sharedPreferences?.edit()?.putString(FAVORITES,temp)?.apply()
}
}
}
这是我在单元测试课程中尝试做的
@RunWith(MockitoJUnitRunner::class)
class AppPreferenceHelperUnitTest {
private var prefhelper: AppPreferenceHelper? = null
private var context: Context = Mockito.mock(Context::class.java)
@Before
fun setUp(){
this.context = Mockito.mock(Context::class.java)
this.prefhelper = Mockito.mock(AppPreferenceHelper::class.java)
prefhelper?.initPreferences(context)
}
@Test
fun testCheckIsFavorite(){
prefhelper?.addFavorite("testId")
verify(prefhelper)?.checkIsFavorite("testId")
}
}
这是我不断收到的错误
Wanted but not invoked:
appPreferenceHelper.checkIsFavorite(
"testId"
);
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。