可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
I successfully mocked
JdbcTemplate jdbcTemplate = getJdbcTemplate(); jdbcTemplate.queryForObject();
with
JdbcTemplate jdbcTemplate = mock(JdbcTemplate.class); when(jdbcTemplate.queryForObject(JdbcTwitterDao.SQL_SELECT_TWITTER, parameterizedRowMapper, 1)).thenReturn(expectedObject);
Would you please let me know how to mock
getJdbcTemplate().queryForObject();
I don't know which object I should mock.
回答1:
If you are using JdbcDaoSupport
as the base class to get the template, you can simply construct your DAO in the test and immediately setJdbcTemplate(mockJdbcTemplate)
on it to replace it with your mock.
回答2:
If you are looking for how to mock variable length parameter methods:
Assuming your DAO class also implements RowMapper interface for mocking method queryForObject(string,rowMapper,Object...)
JdbcTemplate jdbcTemplateMock = Mockito.mock(JdbcTemplate.class); ReflectionTestUtils.setField(yourDao, "jdbcTemplate", jdbcTemplateMock); Mockito.when(jdbcTemplateMock.queryForObject(Mockito.anyString(),Mockito.any(dao.getClass()) ,Mockito.anyVararg())).thenReturn(entity);