kotlinjunitmockitomockito-kotlin

Mockito the purpose of the eq() API?


I’m starting to learn Mockito using Kotlin, and I’m a bit confused about the eq() API.

I’ve noticed that whether I use eq() or not, the following test still PASSES:

@Test
fun init_shouldShowLoading() {
    viewModel.initGame()
    verify(loadingObserver).onChanged(eq(true))
}

What is the difference between using eq() and not using it? When should I use eq()? Thank you so much!


Solution

  • If you only use the eq matcher, it doesn't matter, but if you need to match arguments with different matchers, you need to provide matchers for all arguments.

    This works:

    verify(someMock).someMethod(eq("param1"), eq("param2"))
    

    and so does this:

    verify(someMock).someMethod(eq("param1"), anyString())
    

    but this does not:

    verify(someMock).someMethod("param1", anyString())
    

    This is explicitly covered in the Mockito docs on argument matchers:

    Warning on argument matchers: If you are using argument matchers, all arguments have to be provided by matchers.

    The following example shows verification but the same applies to stubbing:

    verify(mock).someMethod(anyInt(), anyString(), eq("third argument"));
    //above is correct - eq() is also an argument matcher
    
    verify(mock).someMethod(anyInt(), anyString(), "third argument");
    //above is incorrect - exception will be thrown because third argument is given without an argument matcher.