【发布时间】:2012-01-06 09:28:43
【问题描述】:
我想对下面的方法进行单元测试
public void addRecord(Record record)
{
Myclass newObj = new Mycalss();
// It creates newObj object, set some values using record object.
// and it adds the newObj in daatbase.
dataReqDao.persist(newObj);
}
我已经模拟了dataReqDao.persist 方法,但我如何验证是否将正确的值复制到 newObj 对象中?我想得到 newObj 对象。
我认为thenAnswer 将是检索newObj 即方法参数的适当方法,但不知道如何使用它返回void 的方法。
更新:
我试过了
doAnswer(new Answer<Myclass>() {
public Myclass answer(InvocationOnMock invocation) {
Object[] args = invocation.getArguments();
return (Myclass)args[0];
}
}).when(dataReqDao.persist(any(Myclass.class)));
编辑:
应该是(感谢大卫)
doAnswer(new Answer<Myclass>() {
public Myclass answer(InvocationOnMock invocation) {
Object[] args = invocation.getArguments();
return (Myclass)args[0];
}
}).when(dataReqDao).persist(any(Myclass.class));
【问题讨论】:
-
在您的更新中,括号放错了位置。我不确定这是否是您错误的原因,因为其余部分看起来还可以。所以应该是
doAnswer( ... ).when( dataReqDao ).persist( ... );有帮助吗? -
@David:谢谢大卫。实际上我更正了,但忘记更新我的问题。
标签: unit-testing mockito