栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

如何用相同的参数验证相同的模拟方法的调用,该参数会改变模拟中调用之间的状态?

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

如何用相同的参数验证相同的模拟方法的调用,该参数会改变模拟中调用之间的状态?

我创建了以下

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);    }}

此答案捕获正在进行的调用的属性。然后

capturedValues
可以将其用于简单的断言。该实现使用Java 8
API。如果那不可用,则需要使用能够将转换
InvocationOnMock
为捕获值的接口。测试用例中的用法是这样的:

@Testpublic 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();}

Answer
通过Mockitos无法实现由所实现的捕获,
ArgumentCaptor
因为这仅在调用被测方法之后使用。



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/469813.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号