【发布时间】:2019-11-26 12:15:06
【问题描述】:
我有以下类,它使用匿名内部类 (new PreparedStatementSetter()) 在查询中使用 PreparedStatementSetter 设置值并返回对象的 List。
问题是我不确定如何为这种方法编写单元测试。
一旦我的单元测试到达它调用getJdbcTemplate().query(......) 的行,它就会跳到行尾并且discAuditLogList 值返回null 并且单元测试完成而没有任何错误。
当我查看IntelliJ 中的代码覆盖率时,所有ps.setString 语句都没有被执行。
ProductLogDao.java
//bunch of setter getters here
public List<ProductLogDTO> getProductLogDetail(RequestDTO requestDTO) throws SQLException, DataAccessException {
logger.info("Inside ProductLogDao.getProductLogDetail" + requestDTO);
List<ProductLogDTO> productLogList = null;
final Map<String, String> requestParamMap = requestDTO.getParameters();
if ("custom".equalsIgnoreCase(requestParamMap.get("recordtype"))) {
ProductLogList = getProductCustomDetail(senderFeeSql, requestParamMap);
return ProductLogList;
}
return productLogList;
}
public List<ProductLogDTO> getProductCustomDetail(String senderFeeSql,
final Map<String, String> requestParamMap) throws SQLException {
@SuppressWarnings("unchecked")
List<ProductLogDTO> productLogList = getJdbcTemplate().query(senderFeeSql, new PreparedStatementSetter() {
public void setValues(PreparedStatement ps) throws SQLException {
/***************************************************************************************************************/
//FOLLOWING STATMENTS NEVER GET EXECUTED BECAUSE THEY ARE WITHIN ANONYMOUS CLASS (new PreparedStatementSetter())
/***************************************************************************************************************/
ps.setString(1, requestParamMap.get("startDfId"));
ps.setString(2, requestParamMap.get("startDfId"));
ps.setString(3, requestParamMap.get("chanelId"));
ps.setString(4, requestParamMap.get("chanelId"));
ps.setString(5, requestParamMap.get("fromDateTime"));
ps.setString(6, requestParamMap.get("toDateTime"));
ps.setString(7, requestParamMap.get("fromDateTime"));
ps.setString(8, requestParamMap.get("toDateTime"));
}
}, new ProductCustomRowMapper());
if (null != productLogList && (productLogList.size() > 0)) {
productLogList.get(0).setRecordtype("custom");
productLogList.get(0).setRecordsFetched(productLogList.get(0).getRecordsFetched());
}
return productLogList;
}
ProductLogDaoTest.java
public class ProductLogDaoTest {
ProductLogDao instance = new ProductLogDao();
RequestDTO requestDTO = Mockito.mock(RequestDTO.class);
JdbcTemplate jdbcTemplate = Mockito.mock(JdbcTemplate.class);
Map<String, String> requestParamMap = new HashMap<>();
@Before
public void setUp() throws Exception {
instance.setJdbcTemplate(jdbcTemplate);
}
@Test
public void getProductLogDetail_W_Custom() throws SQLException, DataAccessException {
when(requestDTO.getParameters()).thenReturn(requestParamMap);
requestParamMap.put("recordtype", "custom");
assertNotNull(instance.getProductLogDetail(requestDTO));
}
}
【问题讨论】:
标签: java spring junit spring-test spring-test-mvc