Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unit test GeneratedKeyHolder in namedParameterJdbcTemplate

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.

like image 273
Gleeb Avatar asked Apr 07 '14 10:04

Gleeb


1 Answers

I would do this in one of the following ways:

  1. Inject the key.
  2. Stub the method call and set the key there.

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. :)

like image 87
Jamey Avatar answered Nov 08 '22 19:11

Jamey