本文共 786 字,大约阅读时间需要 2 分钟。
我是Mockito的新手.
我试图通过模拟数据库交互来为服务编写jnuit:
我有以下课程(仅代表实际课程)
public class TestService{
public Response getTestList(String type){
list = getListbyType(type);
return response.entity(list);
}
private List getListbyType(String type){
...
..
TestDAO testdao = new Testdao(sqlconn);
list = testdao.getListfromDB(type)
return list;
}
}
我的测试课是这样的
public class TestServiceTest{
@InjectMocks
private TestService testService = new TestService();
@Test
public void getTestListTest(){
List testlist = new List();
tetslist.add("test1");
TestDAO testdaomock = mock(TestDAO);
when(testdaomock.getListfromDB("test")).thenreturn(list);
list = testService.getTestList(test);
}
}
但是,当我运行此测试时,它仍会调用实际的数据库调用并从db而不是模拟值中检索值,我应该模拟sql连接和非默认构造函数吗?我无能为力.
-更新
正如人们所建议的那样,我将DAO实例移到我的服务构造函数中,并且还使用了Spy,但是仍然调用实际的DB调用而不是模拟调用.
转载地址:https://blog.csdn.net/weixin_32601635/article/details/114243196 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!