vendredi 22 mars 2019

Unexpected Mockito Invalid Matchers Exception

I have a method called getTotalResult() that uses 2 other protected methods (namely: getSomeInt() and getAnotherInt() ). Those 2 methods do some calculations and return some number, but that is not what I want to test. What I want to test is the main method that uses then, so getTotalResult(). So I want to mock the other two methods but Mockito gives me an InvalidUseOfMatchersException and I don't know why.

@RunWith(MockitoJUnitRunner.class)
public class CalcTest {

private Calc calc;

@Test
public void getRightCalculation() throws Exception {

    when(calc.getSomeInt(anyInt())).thenReturn(100);
    when(calc.getAnotherInt(anyInt())).thenReturn(1000);

    int result = calc.getTotalResult(42);

    verify(calc, times(1)).getSomeInt(anyInt());
    verify(calc, times(1)).getAnotherInt(anyInt());
    verifyNoMoreInteractions(calc);

    assertEquals(900, result );
    assertTrue(result >= 0);
}

Error log: org.mockito.exceptions.misusing.InvalidUseOfMatchersException: Invalid use of argument matchers! 4 matchers expected, 1 recorded: -> at calculator.CalcTest.getTotalResult(CalcTest.java:37)

This exception may occur if matchers are combined with raw values:
//incorrect:
someMethod(anyObject(), "raw String");
When using matchers, all arguments have to be provided by matchers.
For example:
//correct:
someMethod(anyObject(), eq("String by matcher"));

For more info see javadoc for Matchers class.

Aucun commentaire:

Enregistrer un commentaire