Search code examples
android-studiojunitmockito

@RunWith(MockitoJUnitRunner::class) does not recognize the mockito library


I was trying to use Mockito to have a context for my test, but it it said that I needed to add the library "Gradle: org.mockito:mockito-core:4.0.0", which I already had. I was looking at this page,

Both MockitoJUnitRunner and Mock appeared in red.

@RunWith(MockitoJUnitRunner::class)
class NoticesRepositoryTest {

    private lateinit var noticesRepository: NoticesRepository
    private lateinit var companiesDao: CompaniesDao
    private lateinit var token: String

    @Mock
    private lateinit var context: Context

    (...)
}

These were my imports:

    implementation 'junit:junit:4.12'
    androidTestImplementation 'androidx.test.ext:junit:4.12'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.5.1'
    testImplementation "org.jetbrains.kotlinx:kotlinx-coroutines-test:1.5.2"
    testImplementation "Gradle: org.mockito:mockito-core:4.0.0"
    testImplementation "org.mockito:mockito-inline:4.0.0"
    testImplementation "org.mockito.kotlin:mockito-kotlin:4.0.0"

I put "Gradle:" before the import because the tip to fix the error said to import "Gradle: org.mockito:mockito-core:4.0.0" and I had "org.mockito:mockito-core:4.0.0"


Solution

  • This is how I solved it, in case anyone needs it:

    First of all, Android Studio wasn't recognizing my test directory; I needed to add the directory app/src/test/java/com/example/project and add there my tests. Then I changed all the androidTestImplementation to testImplementation AND added the library "io.mockk:mockk:4.0.0":

        testImplementation 'androidx.test.ext:junit:4.12'
        testImplementation 'androidx.test.espresso:espresso-core:3.5.1'
        testImplementation 'org.jetbrains.kotlinx:kotlinx-coroutines-test:1.7.2'
        testImplementation "org.mockito:mockito-core:4.0.0"
        testImplementation "org.mockito:mockito-inline:4.0.0"
        testImplementation "org.mockito.kotlin:mockito-kotlin:4.0.0"
        testImplementation "io.mockk:mockk:4.0.0"
    

    Now, it should appear the option to import org.mockito.junit.MockitoJUnitRunner in the test file. Otherwise, good luck my friend.