How to mock getJdbcTemplate().queryForObject()?

匿名 (未验证) 提交于 2019-12-03 01:00:01

问题:

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); 


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!