I am trying to write a unit test to a function that holds the following code:
KeyHolder newCode = new GeneratedKeyHolder(); try { namedParameterJdbcTemplate.update(sql, paramMap, newCode); } catch (DuplicateKeyException e) { logger.error("Duplicate Key"); } data.setId(newCode.getKey().intValue());
right now, while using Mockito:
Mockito.when(namedParameterJdbcTemplate.update(Mockito.anyString(), Mockito.any(MapSqlParameterSource.class), Mockito.any(GeneratedKeyHolder.class))).thenReturn(1);
So how am i supposed to fill the GeneratedKeyHolder
with Data?
Thanks.
I would do this in one of the following ways:
Method 1 When I say inject the key I actually mean inject a KeyFactory. This means you can control the result within your test. For example:
KeyHolder newCode = injectedKeyFactory.getKeyHolder();
try {
namedParameterJdbcTemplate.update(sql, paramMap, newCode);
} catch (DuplicateKeyException e) {
logger.error("Duplicate Key");
}
data.setId(newCode.getKey().intValue());
Then in the test:
KeyHolder newCode = mock(KeyHolder.class);
Mockito.when(namedParameterJdbcTemplate.update(Mockito.anyString(), Mockito.any(MapSqlParameterSource.class), newCode)).thenReturn(1);
Mockito.when(newCode.getKey()).thenReturn(__preferredId__);
The key factory is a simple one which just returns a new GeneratedKeyHolder. It gets injected at construction time, so this method does assume you're using DI.
Method 2
Mockito.when(namedParameterJdbcTemplate.update(Mockito.anyString(), Mockito.any(MapSqlParameterSource.class), Mockito.any(GeneratedKeyHolder.class))).thenAnswer(new Answer() {
Object answer(InvocationOnMock invocation) {
Object[] args = invocation.getArguments();
Map<String, Object> keyMap = new HashMap<String, Object>();
keyMap.put("", __preferredId__);
((GeneratedKeyHolder)args[2]).getKeyList().add(keyMap);
}
}).andReturn(1);
I've not really used Mockito, so sorry if the code's not quite right. :)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With