问题描述
我想对以下方法进行单元测试
I want to unit test following method
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 对象.
I have mocked dataReqDao.persist
method but how can I verify if right values are copied into newObj object? I want to get the newObj object.
我认为 thenAnswer
将是检索 newObj 即方法参数的适当方法,但不知道如何使用它返回 void 的方法.
I think thenAnswer
will be the appropraite method to retrieve newObj ie method arguments but dont know how to use it method which returns void.
更新:
我试过
doAnswer(new Answer<Myclass>() {
public Myclass answer(InvocationOnMock invocation) {
Object[] args = invocation.getArguments();
return (Myclass)args[0];
}
}).when(dataReqDao.persist(any(Myclass.class)));
应该是(感谢大卫)
It should be (Thanks David)
doAnswer(new Answer<Myclass>() {
public Myclass answer(InvocationOnMock invocation) {
Object[] args = invocation.getArguments();
return (Myclass)args[0];
}
}).when(dataReqDao).persist(any(Myclass.class));
推荐答案
您可以创建自定义 参数匹配器 将检查该对象的字段,或使用 参数捕获器以捕获对象以供进一步检查.
You can create a custom argument matcher that would check fields of that object, or use an argument captor to capture the object for further inspection.
例如如下:
ArgumentCaptor<Myclass> c = ArgumentCaptor.forClass(Myclass.class);
verify(dateReqDao).persist(c.capture());
Myclass newObj = c.getValue();
... // Validate newObj
这篇关于如何将 thenAnswer 与返回 void 的方法一起使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!