无法在测试中使用 Mockito 和 Kotlin 模拟最终课程

Kir*_*nLy 9 testing mockito kotlin

我正在尝试运行一个简单的仪器测试:

class DefaultTest {

    private val networkHelper = Mockito.mock(NetworkHelperImpl::class.java)

    @Test fun inter() {
        given(networkHelper.isConnectedToNetwork()).willReturn(true)
        assertFalse { networkHelper.isConnectedToNetwork(false) }
    }
}
Run Code Online (Sandbox Code Playgroud)

但我不能因为错误:

Mockito cannot mock/spy because :
- final class
Run Code Online (Sandbox Code Playgroud)

我怎样才能避免它?

正如本指南所说:

https://antonioleiva.com/mockito-2-kotlin/

我正在创建文件:

在此处输入图片说明

有了这条线:

mock-maker-inline

但什么都没有改变。

Gradle 很糟糕(我正在学习),但它必须工作。我也使用单元测试,所以现在我有:

//Tests
testImplementation 'junit:junit:4.13-beta-3'

testImplementation 'org.jetbrains.kotlin:kotlin-stdlib:1.3.41'
testImplementation 'org.jetbrains.kotlin:kotlin-test-junit:1.3.41'

androidTestImplementation 'org.mockito:mockito-core:3.0.0'
androidTestImplementation 'org.mockito:mockito-android:2.24.5'
androidTestImplementation "com.nhaarman.mockitokotlin2:mockito-kotlin:2.1.0"

testImplementation 'org.amshove.kluent:kluent:1.14'

androidTestImplementation 'androidx.test:runner:1.2.0'
androidTestImplementation 'androidx.test:core:1.2.0'
androidTestImplementation 'androidx.test.ext:junit:1.1.1'
androidTestImplementation 'androidx.test:rules:1.2.0'
Run Code Online (Sandbox Code Playgroud)

Jan*_*mar 18

简单地添加

testImplementation("org.mockito:mockito-inline:2.8.47")
Run Code Online (Sandbox Code Playgroud)

解决了这个问题。


小智 8

  1. 按照以下步骤操作:https : //antonioleiva.com/mockito-2-kotlin/
  2. 更新库并替换androidTestImplementationtestImplementation. 就我而言:

    testImplementation "com.nhaarman.mockitokotlin2:mockito-kotlin:2.1.0 (更新)

    testImplementation 'org.mockito:mockito-core:3.0.0'(更新)

    testImplementation 'org.mockito:mockito-android:2.24.5'(用 testImplementation 替换 androidTestImplementation)

  3. 从每个测试类中删除 MockitoAnnotations.initMocks(this)

使用 Android Studio 3.5 测试


you*_*ans 1

你有没有尝试过mockito-kotlin?将其添加到您的依赖项中:

testImplementation "com.nhaarman.mockitokotlin2:mockito-kotlin:2.1.0"

Run Code Online (Sandbox Code Playgroud)

  • 我补充道,但没有任何改变。 (5认同)