首页 > 解决方案 > 由于 mockito,Android 仪器测试失败

问题描述

嗨,我收到以下错误


org.koin.error.BeanInstanceCreationException: Can't create definition for 'Single [name='NetworkControllerContract',class='com.network.contract.NetworkControllerContract']' due to error :

Mockito cannot mock this class: class com.network.NetworkController.

我已经手动打开了这些课程..

open class NetworkController constructor(private val networkHelper: NetworkHelperContract) : NetworkControllerContract{.....}

open interface NetworkControllerContract {
}

//my test class

@RunWith(AndroidJUnit4::class)
class MyUnitTest: KoinTest {

   single<NetworkControllerContract> {
            Mockito.mock(NetworkController::class.java) //where it crashes
        }

   val networkController: NetworkControllerContract by inject()

}

我使用的依赖项


   def mockito = "2.21.0"

//android instrumental test
    androidTestImplementation 'junit:junit:4.12'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.1.1'
    androidTestImplementation 'androidx.test.ext:junit:1.1.0'
    androidTestImplementation 'androidx.test.ext:truth:1.1.0'
    androidTestImplementation 'androidx.test:core:1.1.0'
    androidTestImplementation 'androidx.test:runner:1.1.1'
    androidTestImplementation('androidx.arch.core:core-testing:2.0.0') {
        exclude group: 'org.mockito:mockito-core'
    }
    androidTestUtil 'androidx.test:orchestrator:1.1.1'
    androidTestImplementation 'com.github.tmurakami:dexopener:2.0.0'

    androidTestImplementation 'com.jraska.livedata:testing-ktx:0.6.0'
    androidTestImplementation 'com.jraska.livedata:testing:0.6.0'

    androidTestImplementation "org.mockito:mockito-core:$mockito"
    androidTestImplementation("org.mockito:mockito-android:$mockito") {
        exclude group: 'org.mockito'
    }

    androidTestImplementation('org.koin:koin-test:1.0.2') {
        exclude group: 'org.mockito'
    }

 testImplementation 'junit:junit:4.12'
    testImplementation "org.mockito:mockito-core:$mockito"
    testImplementation "org.mockito:mockito-android:$mockito"
    testImplementation "org.mockito:mockito-inline:$mockito"
    testImplementation 'org.koin:koin-test:1.0.2'
    testImplementation 'androidx.test.ext:junit:1.1.0'
    testImplementation 'androidx.arch.core:core-testing:2.0.0'
    testImplementation 'com.jraska.livedata:testing-ktx:0.6.0'
    testImplementation 'com.jraska.livedata:testing:0.6.0'
    testImplementation 'androidx.test.ext:truth:1.1.0'

标签: unit-testingkotlinandroid-instrumentationkoin

解决方案


问题出在您的设置中:

testImplementation "org.mockito:mockito-android:$mockito"

此依赖项使用 Android 内部,在运行单元测试时不可用。


推荐阅读