Reputation: 31242
I am trying to mock jdbcTemplate to throw an exception.
I am trying to throw exception on this method on JdbcTemplate
<T> List<T> query(String sql, Object[] args, RowMapper<T> rowMapper)
Here is what I have
@MockBean
JdbcTemplate jdbcTemplate;
Mockito.doThrow(exception).when(jdbcTemplate.query(anyString(), anyList(), any(MyMapper.class)));
I get compilation error, cannot resolve method
. I also tried
Mockito.doThrow(exception).when(jdbcTemplate.query(anyString(), anyList(), Matchers.<RowMapper<MyMapper>>any()));
but still get same error.
what is the right way to do it here?
EDIT
As suggested in one of the answers, I tried
Mockito.doThrow(exception).when(jdbcTemplate).query(anyString(), anyList(), any(MyMapper.class));
I still get cannot resolve the method
error.
Upvotes: 1
Views: 2877
Reputation: 47865
The following calls will compile:
Mockito.doThrow(exception).when(jdbcTemplate).query(
Mockito.anyString(),
Mockito.any(Object[].class),
Mockito.any(MyMapper.class)
);
Mockito.doThrow(exception).when(jdbcTemplate).query(
Mockito.anyString(),
Mockito.any(Object[].class),
ArgumentMatchers.<RowMapper<MyMapper>>any())
);
The key difference between these and what you had tried previously is the second argument. In this method:
<T> List<T> query(String sql, Object[] args, RowMapper<T> rowMapper) throws DataAccessException;
... the second argument is:
Object[] args
It looks like you were matching this with anyList()
which returns List<T>
. Since this parameter is of type Object[]
it should be matched with something which returns an Object[]
. For example:
Mockito.any(Object[].class)
Upvotes: 8
Reputation: 516
Try:
Mockito.doThrow(exception).when(jdbcTemplate).query(anyString(), anyList(), any(MyMapper.class));
The when()
call is to wrap your mock; you don't call your method within the when()
call you do it after that wrapping to indicate to Mockito what you are expecting to happen to it.
Upvotes: 0