【发布时间】:2016-04-07 14:19:33
【问题描述】:
我有一些这样的结构
...
SomeDao dao = getDAO(AttributeDAO.class);
CustomType type =dao.findByKey(typeOne, typeTwo, typeThree.toString());
if(type == null) {
System.out.print("null returned");
} else {
System.out.print("do something");
}
...
我的测试用例
...
MainClass mc = Mockito.spy(new MainClass());
CustomType type = new CustomType();
SomeDao dao = Mockito.mock(AttributeDAO.class);
type.setValueOne(1);
type.setValueTwo(1);
type.setValueThree("Y");
Mockito.doReturn(type).when(dao).findByKey(1,2,"Y");
mc.callThisDaoFunction();
...
但每当我尝试使用 eclemma 覆盖工具返回类型时,它总是说type == null 我如何测试用例或设置类型以返回非空值?
【问题讨论】:
-
我认为您需要覆盖该 getDAO() 方法的行为以返回您的模拟 DAO...否则,模拟可能不会被调用,而且您的实际 SUT 可能没有已为测试进行了充分配置(即,类型实际上为空)。我倾向于使用 JMockit,它会进行字节码替换,这样只需注释模拟 DAO 即可替换 SUT 中的 DAO,而无需您付出额外的努力。
-
所以,可能,因为你有一个间谍......在创建你的 CustomType.. Mockito.doReturn(type).when(mc).getDAO(anyObject());
-
我看到,阅读@Alexander 的回复,我的意思是 Mockito.doReturn(dao) 而不是上面的 Mockito.doReturn(type)。这似乎将点点滴滴联系起来..
标签: java unit-testing junit mockito