Ivan
Ivan

Reputation: 617

Testing Kotlin classes with Mockito causes MissingMethodInvocationException

So after alot of trail and error with a kotlin class i found that the same code in java is testable but not testable with kotlin.

@RunWith(MockitoJUnitRunner.class)
public class TestStuff {
    @Mock
    B b;

    @Test
    public void testStuff(){
        A a = new A(b);
        Mockito.when(b.provideValue()).thenReturn("");
        a.doStuff();
    }
}


class A(val b: B) {

    fun doStuff() {
        b.provideValue()
    }
}

open class B {
    fun provideValue(): String {
        return "b"
    }
}

This causes: org.mockito.exceptions.misusing.MissingMethodInvocationException: when() requires an argument which has to be 'a method call on a mock'. For example: when(mock.getArticles()).thenReturn(articles);

But if i write class B as a java class i.e.

public class B {
    public String provideValue(){
        return "b";
    }
}

The test works. Can some one explain why this is happening or how am i suposed to test kotlin code when mockito does not work consistently.

Upvotes: 2

Views: 813

Answers (1)

Roland
Roland

Reputation: 23232

Mockito has problems with final classes or methods. As everything is final by default in Kotlin, you need to either write open fun provideValue() : String or use another mocking library or skip mocking at all ;-)

so your Java-class actually translated to Kotlin would look as follows (simplified):

open class B {
  open fun provideValue() = "b"
}

Just today I've heard of mockk and I tried your example. With that library you will not need to open up your classes and methods just for testing purposes, so you maybe want to take a look at it.

Upvotes: 3

Related Questions