Narasimha Reddy
Narasimha Reddy

Reputation: 59

How to mock jdbctemplate.query() method?

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.

Upvotes: 4

Views: 29057

Answers (3)

ChristianRein
ChristianRein

Reputation: 96

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.

Upvotes: 7

Akshay Chopra
Akshay Chopra

Reputation: 1253

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);

Upvotes: 3

Mart&#237;n Zaragoza
Mart&#237;n Zaragoza

Reputation: 1817

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

Upvotes: 3

Related Questions