gpt4 book ai didi

java - 调用模拟对象的方法时如何验证返回值

转载 作者:塔克拉玛干 更新时间:2023-11-02 07:48:58 25 4
gpt4 key购买 nike

使用 Mockito,有没有办法在一个对象上进行 spy() 并验证一个对象是否使用指定的参数被调用了给定的次数,并且它是否返回了这些调用的预期值?

我想做如下的事情:

class HatesTwos {
boolean hates(int val) {
return val == 2;
}
}

HatesTwos hater = spy(new HatesTwos());
hater.hates(1);
assertFalse(verify(hater, times(1)).hates(1));

reset(hater);
hater.hates(2);
assertTrue(verify(hater, times(1)).hates(2));

最佳答案

您可以使用 Answer 界面来捕获真实响应。

public class ResultCaptor<T> implements Answer {
private T result = null;
public T getResult() {
return result;
}

@Override
public T answer(InvocationOnMock invocationOnMock) throws Throwable {
result = (T) invocationOnMock.callRealMethod();
return result;
}
}

预期用途:

class HatesTwos {
boolean hates(int val) {
return val == 2;
}
}

HatesTwos hater = spy(new HatesTwos());

// let's capture the return values from hater.hates(int)
ResultCaptor<Boolean> hateResultCaptor = new ResultCaptor<>();
doAnswer(hateResultCaptor).when(hater).hates(anyInt());

hater.hates(1);
verify(hater, times(1)).hates(1);
assertFalse(hateResultCaptor.getResult());

reset(hater);

hater.hates(2);
verify(hater, times(1)).hates(2);
assertTrue(hateResultCaptor.getResult());

关于java - 调用模拟对象的方法时如何验证返回值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18906983/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com