4
Mokito.when(jdbcTemplate.query(sql, new ParticipantMapper())).thenReturn(participantExistingList); 

I am using above line of code for Mocking jdbcTemplate but its not working. Can some one will help how to mock jdbcTemplate.

2
  • Use Mockito.any(ParticipantMapper.class) instead of new ParticipantMapper() Commented Sep 11, 2018 at 12:49
  • org.mockito.exceptions.misusing.InvalidUseOfMatchersException: Invalid use of argument matchers! 2 matchers expected, 1 recorded: Getting this error after adding above code. Commented Sep 11, 2018 at 13:25

3 Answers 3

7

Use ArgumentMatchers for all Arguments, like this:

Mockito.when(jdbcTemplate.query(any(String.class), any(ParticipantMapper.class))) .thenReturn(participantExistingList); 

Depending on your wish to focus the interaction, you may use e.g. eq() for your sql String.

See here for JavaDoc.

Sign up to request clarification or add additional context in comments.

Comments

3

Try doing this:

On your test class use:

 @Mock JdbcTemplate jdbcTemplate; 

Then try:

Mokito.when(jdbcTemplate.query(sql, new ParticipantMapper())).thenReturn(participantExistingList); 

If it still fails, try:

doReturn(participantExistingList).when(jdbcTemplate).query(sql, new ParticipantMapper()); 

Hope this helps

Comments

3

Its important to see the order of your parameters inside query() method.

In my case, I wanted to mock for the following line:

List<String> someList = jdbcTemplate.query(SQL_STRING,new Object[] { Id }, new MyCustomMapper()); 

So I mocked it the following way, taking care of the order of parameters passed

when(jdbcTemplate.query(any(String.class),(Object[]) anyVararg(),any(MyCustomMapper.class))).thenReturn(myList); 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.