我想对下面的方法进行单元测试
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));
最佳答案
您可以创建自定义 argument matcher这将检查该对象的字段,或使用 argument captor捕获对象以供进一步检查。
例如如下:
ArgumentCaptor<Myclass> c = ArgumentCaptor.forClass(Myclass.class);
verify(dateReqDao).persist(c.capture());
Myclass newObj = c.getValue();
... // Validate newObj
关于unit-testing - 如何将 thenAnswer 与返回 void 的方法一起使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8755753/