55

The simple test case below is failing with an exception.

org.mockito.exceptions.misusing.InvalidUseOfMatchersException:
Invalid use of argument matchers! 3 matchers expected, 2 recorded:

I am not sure what is wrong

@Test
public void testGetStringTest(){
    final long testId = 1;
    String dlrBAC = null;
    NamedParameterJdbcTemplate jdbcTemplate = mock(NamedParameterJdbcTemplate.class);
    when(this.dao.getNamedParameterJdbcTemplate()).thenReturn(jdbcTemplate);
    when(jdbcTemplate.queryForObject(
        anyString(), 
        any(SqlParameterSource.class), 
        String.class
    )).thenReturn("Test");
    dlrBAC =  dao.getStringTest(testId);
    assertNotNull(dlrBAC);
}
william xyz
  • 710
  • 5
  • 19
Anwar
  • 553
  • 1
  • 4
  • 6

2 Answers2

113

Mockito requires you to either use only raw values or only matchers when stubbing a method call. The full exception (not posted by you here) surely explains everything.

Simple change the line:

when(jdbcTemplate.queryForObject(
    anyString(),
    any(SqlParameterSource.class), 
    String.class
)).thenReturn("Test");

to

when(jdbcTemplate.queryForObject(
    anyString(), 
    any(SqlParameterSource.class), 
    eq(String.class)
)).thenReturn("Test");

and it should work.

william xyz
  • 710
  • 5
  • 19
makasprzak
  • 5,082
  • 3
  • 30
  • 49
  • 2
    add `import static org.mockito.Mockito.*;` – makasprzak Jun 28 '14 at 18:49
  • 1
    above change gives compile time error as "The method eq(Class) is undefined for the type test class – Anwar Jun 28 '14 at 18:50
  • add the static import I just mentioned – makasprzak Jun 28 '14 at 18:51
  • 2
    Hope my understanding is correct: If you are using any matcher for any 1 argument then you need to use matcher for all other arguments as well for a method or do not use matcher at all and pass actual value/object. – dkb May 16 '18 at 07:01
  • 3
    Very old post, but for the Scala programmers that end up here (like myself), you'll find out that adding `import org.mockito.Mockito._` and then calling `eq(classOf[String])` won't work. The solution is to use the full path of the `eq()` function: `org.mockito.Matchers.eq(classOf[String]))` as stated [here](https://stackoverflow.com/a/29524445/5420229). – Hannon Queiroz Jun 13 '18 at 11:20
  • (scala) org.mockito.Matchers is deprecated, alternative is org.mockito.ArgumentMatchers.eq – Ikrom Aug 04 '20 at 21:58
  • I'm getting this error using none of "real value", only matchers static functions. – Odravison Jul 26 '21 at 10:16
0

For me I was using EasyMock and it was the wrong import. Make sure you have the correct imports of (anyString, any, anyInt).