I'm creating a unit test for the below Java code which gets data from a database and, via a lambda, maps the data retrieved into a list:
List<Pair<String, String>> list = jdbcTemplate.query(MY_QUERY, (rs, rowNum) -> {
String code = rs.getString(1);
String name = rs.getString(2);
return new Pair<String, String>(code, name);
});
It's part of a Spring framework service class; the unit test is run via SpringJUnit4ClassRunner.
I've used Mockito to mock the jdbcTemplate object (of type NamedParameterJdbcTemplate).
I'm trying to mock the result of the jdbcTemplate. Looking at the method call, it looks like I need to mock this method in the NamedParameterJdbcTemplate class:
query(String sql, RowMapper<T> rowMapper)
I have tried this:
List<Pair<String, String>> pairList = ...;
Mockito.when(jdbcTemplate.query(Mockito.anyString(), Mockito.any(RowMapper.class))).thenReturn(pairList);
... but when I run the unit test, the "list" variable is always null after the line of code has been passed, as if the mock hasn't been triggered to return my value.
The Mockito object is definitely being injected into the class.
Printing the mock's invocactions displays this:
[Mockito] Interactions of: Mock for NamedParameterJdbcTemplate, hashCode: <n>
1. namedParameterJdbcTemplate.query("query", my.package.MyClass$$Lambda$114/1274225913@3e134896);
Is there anything I'm obviously doing wrong? Thanks in advance for any assistance.