unit-testing - 如何将 thenAnswer 与返回 void 的方法一起使用

标签 unit-testing mockito

我想对下面的方法进行单元测试

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/

相关文章:

c# - 测试 Entity Framework 模型

oracle - 在 SQL Developer 的单元测试框架中验证 PL/SQL 存储过程 OUT REF CURSOR

java - Mockito 中模拟方法的单元测试最佳实践

java - 尝试使用 junit5 和 mockito 模拟 byte[] 值时出现空值

android - Android单元测试中资源文件访问 "InvocationTargetException"

java - 如何从mockito中的另一个包访问 protected 方法?

unit-testing - 我们如何拥有单元测试理念?

javascript - 如何检查 $httpBackend 中是否未进行 GET 调用

Angular 11 : Unit testing an HttpInterceptor - can't get catchError to work in test

java - 渲染时定义的 Spring Webflow 操作未在单元测试中调用