我正在尝试测试dao,但是当我传递anyString()时,在dao中它以空字符串形式出现,因此,它没有返回我想要的模拟对象
@InjectMocks
private Dao dao;
@Mock
@Qualifier("jdbcTemp")
private JdbcTemplate jdbcTemp;
@Test
public void testGetData() {
List<MyObj> list = new ArrayList<>();
MyObj myObj = new MyObj();
myObj.setMethod("method val");
list.add(myobj);
Mockito.when(jdbcTemp.query(anyString(), Mockito.any(PreparedStatementSetter.class),
Mockito.any(Dao.MyRowMapper.class))).thenReturn(list);
List<MyObj> res = dao.getData(param1, param2); // this is empty, instead of having a value of 1
Assertions.assertThat(res).isNotNull();
}
我的道
@Autowired
private String query;
@Autowired
private JdbcTemplate jdbcTemp;
public List<MyObj> getData(String arg1, String arg2) {
List<MyObj> list = new ArrayList<MyObj>();
try {
// query below is null instead of empty string
list.addAll(jdbcTemp.query(query, new PreparedStatementSetter() {
public void setValues(PreparedStatement pstmt) throws SQLException {
pstmt.setString(PARAM_ONE, arg1);
pstmt.setString(PARAM_TWO, arg2);
}
}, new MyRowMapper()));
} catch (Exception exp) {
}
return list;
}
答案 0 :(得分:0)
因此,正如您所正确提到的,anyString()
仅适用于非空字符串。并且当您将query
传递到方法中时,应验证自动连接的query
是否不为空。
或者,您可以坚持使用any()
或nullable(String.class)
来匹配null。由于您的测试不依赖于query
值,因此可以放心使用它。
但是,由于您的代码未显示注入的工作方式,因此我们无法进一步调查您的问题。如果您需要这样做,请添加相关的代码部分。