How to set up Mockito for Kotlin and Android

Viewed 8794

I want to use Mockito for unit testing, so I added the Mockito library into my gradle dependencies.

testImplementation 'junit:junit:4.12'
testCompile 'org.mockito:mockito-core:2.12.0' 

But still, I can not use any Mockito annotations.

/androidTest/ExampleTest.kt

@RunWith(MockitoJUnitRunner::class) // Unresolved reference MockitoJUnitRunner
@Mock // Unresolved reference Mock

What I'm missing it?

4 Answers

You need to add the following dependencies in your app's build.gradle:

dependencies {
    // ... more entries
    testCompile 'junit:junit:4.12'

    // required if you want to use Mockito for unit tests
    testImplementation 'org.mockito:mockito-core:2.24.5'
    // required if you want to use Mockito for Android tests
    androidTestImplementation 'org.mockito:mockito-android:2.24.5'
}

And click on sync

You may need another dependency:

androidTestCompile 'org.mockito:mockito-android:2.12.0'

Alternatively, you can try manually importing the annotations:

import static org.mockito.Mockito.*;

It could be that it didn't import properly and that's why it showed as an unresolved reference. Auto-import has its flaws

I have faced an issue with assembleDebugAndroidTest which is related to objenesis. So, based on Shylendra's answer, you may want to replace

androidTestImplementation 'org.mockito:mockito-android:2.24.5'

with

androidTestImplementation("org.mockito:mockito-core:2.8.47")

Very confortable library over mockito:

    testImplementation 'org.mockito:mockito-inline:2.21.0'
    testImplementation('com.nhaarman.mockitokotlin2:mockito-kotlin:2.2.0') {
        exclude group: 'org.jetbrains.kotlin'
        exclude group: 'org.mockito'
    }

    // Also works like a charm with instrumentation tests
    androidTestImplementation 'org.mockito:mockito-android:3.5.13'
    androidTestImplementation('com.nhaarman.mockitokotlin2:mockito-kotlin:2.2.0') {
        exclude group: 'org.jetbrains.kotlin'
        exclude group: 'org.mockito'
    }
Related