Kitesurfer
Kitesurfer

Reputation: 3561

mocking internal classes with mockito

i have a class under Test which is marked as "interal"

internal class UnderTest{
    fun methodToTest(){}
}

In my JUnit Test i want test UnderTest import com.nhaarman.mockito_kotlin.mock

class SimpleTest{
    val mock = mock<UnderTest>()

    @Test
    fun test(){
        assertThat(....)
    } 
}

And here it gets a bit strange, as Android Studio complains first that UnderTest is not visible "public property exposes it's private type". Thats because UnderTest is marked as internal.

I changed the Test itself to be internal, which results that the compiler is happy again:

import com.nhaarman.mockito_kotlin.mock

internal class SimpleTest{
    val mock = mock<UnderTest>()

    @Test
    fun test(){
        assertThat(....)
    } 
}

Running this test results in an mockito exception like in the old mockito versions

Cannot mock/spy class com.name.UnderTest
Mockito cannot mock/spy because :
- final class

I want to write Unit Test for those internal classes, but how without removing the internal modifier from UnderTest class ?

Thanks

Upvotes: 0

Views: 3284

Answers (1)

user2340612
user2340612

Reputation: 10733

The issue is not that the class is internal (it's equivalent to public within the same module) but rather that it's final. By default all classes in Kotlin are final unless you mark them with open.

So if you want to mock your class you should mark it as internal open class Xyz. Note that there's a Maven/Gradle plugin that automatically opens all classes for you: all-open plugin.

For example, given the following Kotlin class:

internal open class Foo

The following unit test passes:

class FooTest {
    @Test
    fun shouldPass() {
        Mockito.mock(Foo::class.java)
    }
}

Upvotes: 3

Related Questions