Expert wanna be
Expert wanna be

Reputation: 10624

How to set up Mockito for Kotlin and Android

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?

Upvotes: 9

Views: 13696

Answers (4)

Link182
Link182

Reputation: 839

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'
    }

Upvotes: 0

Andrii Artamonov
Andrii Artamonov

Reputation: 648

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")

Upvotes: 0

Shailendra Madda
Shailendra Madda

Reputation: 21561

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

Upvotes: 39

Zoe - Save the data dump
Zoe - Save the data dump

Reputation: 28278

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

Upvotes: 4

Related Questions