如何使用在mockito中调用之间更改状态的相同参数来验证相同模拟
发布时间:2020-12-15 04:33:42 所属栏目:Java 来源:网络整理
导读:我有以下代码进行单元测试: public void foo() { Entity entity = //... persistence.save(entity); entity.setDate(new Date()); persistence.save(entity);} 我想验证在第一次调用persistence.save时,entity.getDate()返回null. 因此,我无法使用Mockito.v
|
我有以下代码进行单元测试:
public void foo() {
Entity entity = //...
persistence.save(entity);
entity.setDate(new Date());
persistence.save(entity);
}
我想验证在第一次调用persistence.save时,entity.getDate()返回null. 因此,我无法使用Mockito.verify(/*…*/),因为那时方法foo已经完成并且调用了entity.setDate(Date). 所以我认为我需要在调用发生时对调用进行验证.我如何使用Mockito做到这一点? 解决方法
我创建了以下Answer实现:
public class CapturingAnswer<T,R> implements Answer<T> {
private final Function<InvocationOnMock,R> capturingFunction;
private final List<R> capturedValues = new ArrayList<R>();
public CapturingAnswer(final Function<InvocationOnMock,R> capturingFunction) {
super();
this.capturingFunction = capturingFunction;
}
@Override
public T answer(final InvocationOnMock invocation) throws Throwable {
capturedValues.add(capturingFunction.apply(invocation));
return null;
}
public List<R> getCapturedValues() {
return Collections.unmodifiableList(capturedValues);
}
}
此答案捕获正在进行的调用的属性.捕获的值可以用于简单的断言.该实现使用Java 8 API.如果这不可用,则需要使用能够将InvocationOnMock转换为捕获值的接口.测试用例中的用法如下: @Test
public void testSomething() {
CapturingAnswer<Void,Date> captureDates = new CapturingAnswer<>(this::getEntityDate)
Mockito.doAnswer(captureDates).when(persistence).save(Mockito.any(Entity.class));
service.foo();
Assert.assertNull(captureDates.getCapturedValues().get(0));
}
private Date getEntityDate(InvocationOnMock invocation) {
Entity entity = (Entity)invocation.getArguments()[0];
return entity.getDate();
}
使用Mockitos ArgumentCaptor无法实现由呈现的Answer实现完成的捕获,因为这仅在调用被测方法之后使用. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
