我不能用Mockito 2模拟Kotlin期末班.另外我还在用Robolectric.

这是我的测试代码:

@RunWith(RobolectricTestRunner.class)
@Config(constants = BuildConfig.class, sdk = 21)
public class Test {

    // more mocks

    @Mock
    MyKotlinLoader kotlinLoader;

    @Before
    public void setUp() {
        MockitoAnnotations.initMocks(this);
    }
}

当我们try 在setUp()方法中初始化模拟时,测试失败.

In addition, I am using the following gradle dependencies in my code:

testCompile 'org.robolectric:robolectric:3.3.2'
testCompile 'org.robolectric:shadows-multidex:3.3.2'
testCompile 'org.robolectric:shadows-support-v4:3.3.2'
testCompile("org.powermock:powermock-api-mockito2:1.7.0") {
    exclude module: 'hamcrest-core'
    exclude module: 'objenesis'
}
testCompile 'junit:junit:4.12'
testCompile 'org.mockito:mockito-inline:2.8.9'

All other unit tests pass using this configuration but as soon as I try to mock the Kotlin class it throws the following error:

Mockito cannot mock/spy because : - final class

请注意,我使用的是Mockito版本2,我使用的是inline依赖项,它自动启用模拟最终类的能力.

推荐答案

您可以为此使用Powermock,例如:

import static org.powermock.api.mockito.PowerMockito.mock;
import static org.powermock.api.mockito.PowerMockito.spy;
import static org.powermock.api.mockito.PowerMockito.when;

@RunWith(RobolectricTestRunner.class)
@Config(constants = BuildConfig.class, sdk = 21)
@PowerMockIgnore({ "org.mockito.*", "org.robolectric.*", "android.*" })
@PrepareForTest({FinalClass1.class, FinalClass2.class})
public class Test {
    @Rule
    public PowerMockRule rule = new PowerMockRule();

    ... // your code here
}

Kotlin相关问答推荐

文本正在被切断在200%的屏幕比例在Jetpack Compose

判断字符串是否除了.&" ",","@""""

jOOQ Kotlin Coroutines - Select all and exists查询

有什么方法可以要求在 kotlin 中的类型参数上进行注释?

如何在 kotlin 中创建自定义迭代器并添加到现有类?

如何限制 Kotlin 中的枚举?

如何将glide显示的图像下载到设备存储中.Kotlin

为 Gradle 子项目配置 Kotlin 扩展

Kotlin 方法重载

runOnUiThread 没有调用

作为 Kotlin 中的函数的结果,如何从 Firestore 数据库返回列表?

@uncheckedVariance 在 Kotlin 中?

Kotlin - 来自 KType 的 KClass<*>

如果 Maybe 完成,则从其他来源将 Maybe 转换为 Single

Kotlin 中的内联构造函数是什么?

Kotlin通过映射委托属性,如果映射中不存在,则抛出NoTouchElementException

Kotlin/JS,Gradle 插件:无法加载@webpack-cli/serve命令

Kotlin扩展函数与成员函数?

@StringRes、@DrawableRes、@LayoutRes等android注释使用kotlin参数进行判断

如何在 Kotlin 中定义新的运算符?