英文:
Mocked Object not returning expected value
问题
我正在对我的 dao 进行单元测试。我创建了一个列表,往列表中添加了一个对象,然后我告诉 mockito 当调用我的方法时,返回一个带有单个对象的列表。然而,当我查看从 dao 方法返回的内容时,得到的却是一个空列表。我不确定我漏掉了什么。
@InjectMocks
private Dao dao;
@Mock
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); // 这是空的,而不是一个值为 1 的列表
Assertions.assertThat(res).isNotNull();
}
我的 Dao 类:
public List<MyObj> getData(String arg1, String arg2) {
List<MyObj> list = new ArrayList<MyObj>();
try {
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;
}
英文:
I'm unit testing my dao. I create a list, I add an object to my list and I tell mockito when my method is called, to return my list with a single object. However, when I look at what's returned from my dao method, it's an empty list. I'm not sure what I'm missing.
@InjectMocks
private Dao dao;
@Mock
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();
}
My Dao class:
public List<MyObj> getData(String arg1, String arg2) {
List<MyObj> list = new ArrayList<MyObj>();
try {
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;
}
答案1
得分: 1
我在描述问题时实际上犯了一个错误。
我的 dao 中有两个 jdbcTemplates。
所以我解决的方法是在创建模拟 jdbctemplate 时使用 @Qualifier("jdbcTemplate")
。
英文:
I actually made a mistake in describing the problem.
I had two jdbcTemplates in my dao.
So the way I resolved it is to use a @Qualifier("jdbcTemplate")
when creating a mock jdbctemplate
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论