使用 java 8 编写的 DAO 类方法的 Mockito 测试用例


public class DBConnectionDAOImpl {
public List<String> getData{
    return jdbcTemplate.query("Select abc from table_name ", (ResultSet rs) -> getAllData(rs));
}
public List<String> getAllData(ResultSet rs){
    List<String> ls = new ArrayList<>();
    try{
        while(rs.next()){
            ls.add(rs.getString("pk"));
        }
        return ls;
    }catch(Exception e){

    }
}

}

为了测试getData方法,我将测试用例编写为:

public class DBConnectionDAOImplTest {
@InjectMock
DBConnectionDAOImpl dbConnectionDAOImpl;
@MOck
JdbcTemplate jdbcTemplate;
@Test
public void getDataTest(){
    ResultSet rs = Mockito.mock(ResultSet.class);
    when(rs.next().thenReturn(true).thenReturn(false));
    when(rs.getString("pk")).thenReturn("someVal");
    when(dbConnectionDAOImpl.getAllData(rs)).thenReturn(new ArrayList<String>());
    when(jdbcTemplate.query("Select abc from table_name ", (ResultSet rs) -> dbConnectionDAOImpl.getAllData(rs))).thenReturn(new ArrayList<String>());
    List<String> result = dbConnectionDAOImpl.getData();
    assertNotNull(result);
}

}

运行测试用例时,我收到错误

when(dbConnectionDAOImpl.getAllData(rs)).thenReturn(new ArrayList<String>());

作为"org.mockito.exceptions.misusing.WrongTypeOfReturnValue:"。不知道我到底错在哪里。

---编辑1--更改后

 when(dbConnectionDAOImpl.getAllData(rs)).thenReturn(new ArrayList<String>());

根据注释断言失败。

如我评论中提供的链接,尝试更改:

when(dbConnectionDAOImpl.getAllData(rs)).thenReturn(new ArrayList<String>());

doReturn(new ArrayList<String>()).when(dbConnectionDAOImpl).getAllData(rs)

相关内容

  • 没有找到相关文章

最新更新