使用Mockito中的访问器模拟Kotlin属性 [英] Mocking kotlin property with accessors in Mockito

查看:86
本文介绍了使用Mockito中的访问器模拟Kotlin属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的应用程序类(Kotlin)中有一个基于SharedPreferences值的令牌属性

I have a token property in my application class(Kotlin) that is based on a SharedPreferences value

    var token : String?
    get() = PreferenceManager.getDefaultSharedPreferences(applicationContext)
               .getString(TOKEN_PEREF_TAG, null)
    set(value) {
    PreferenceManager.getDefaultSharedPreferences(applicationContext)
            .edit()
            .putString(TOKEN_PEREF_TAG, value)
            .apply()
    }

问题是我无法设置这样的模拟值:

The problem is that I can't set a mock value like this:

whenever(app.token).thenReturn("token")

因为我得到了错误

java.lang.RuntimeException:android.preference.PreferenceManager中的方法getDefaultSharedPreferences不被模拟.

java.lang.RuntimeException: Method getDefaultSharedPreferences in android.preference.PreferenceManager not mocked.

模拟不应该只返回提供的字符串吗?

Shouldn't the mock just return the provided string?

如何解决该错误?

推荐答案

您可以通过使用mockito-inline依赖性而​​不是mockito-core依赖性来解决此错误.这使用了一种不同的模拟方法来避免平台类不可用的问题.它也特别有用,因为它允许您模拟最终课程,因此无需将每个课程都放在一个界面,或在Kotlin中将其标记为open.

You can fix this error by using the mockito-inline dependency instead of the mockito-core dependency. This uses a different mocking method that circumvents this issue of the platform classes not being available. It's also particularly useful because it allows you to mock final classes, therefore eliminating the need to put every one of your classes behind an interface or mark them as open in Kotlin.

此内联模拟方法也可以通过

This inline mocking method can also be turned on by a configuration file, however I found just using the inline dependency much more reliable.

这篇关于使用Mockito中的访问器模拟Kotlin属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆