我想单元测试下面的方法如何使用thenAnswer与方法,该方法返回void
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 ie方法参数但不知道如何使用它返回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(...);'这有帮助吗? – 2012-01-10 22:56:41
@David:谢谢大卫。其实我纠正了,但忘记更新我的问题。 – xyz 2012-01-11 05:45:41