gpt4 book ai didi

java - Mockito 的参数捕捉器行为

转载 作者:搜寻专家 更新时间:2023-11-01 02:20:03 25 4
gpt4 key购买 nike

我面临一个问题,我需要跟踪某些方法的调用,但只能使用指定的参数参数。请参阅下面的问题

@Test
public void simpleTest() {
ArgumentCaptor<Pear> captor = ArgumentCaptor.forClass(Pear.class);
Action action = mock(Action.class);
action.perform(new Pear());
action.perform(new Apple());
verify(action, times(1)).perform(captor.capture());
}

static class Action {

public void perform(IFruit fruit) {}

}
static class Pear implements IFruit {}
static class Apple implements IFruit {}

interface IFruit {}

但是得到:

org.mockito.exceptions.verification.TooManyActualInvocations: 
action.perform(<Capturing argument>);
Wanted 1 time:
But was 2 times. Undesired invocation:
..

我做错了什么? Mockito v 1.10

老实说,这只是例子,我的代码比较复杂,我不知道,Apple.class 会调用多少次 perform。对我来说没关系。我只需要验证 perform(Pear.class) 的调用

更新:我需要验证 Pear.class 的方法是否被调用过一次。假设 Action 是 Transaction,执行是 save(DomainObject)。所以我需要确保 save(MyDomainObject) 被调用了一次,但不管之前保存了多少对象。此操作对于测试来说是原子的,我无法在这些操作之间重置模拟

最佳答案

要使用 Pear 实例参数验证调用次数,您可以使用:

verify(action, times(1)).perform(isA(Pear.class));

比照。 Mockito. Verify method param to be a paticular class

请注意,从 Mockito 2.1 开始,以下内容也可以使用:

verify(action, times(1)).perform(any(Pear.class));

比照。 public static T any(Class type)

...This is an alias of: isA(Class)...

...Since mockito 2.1.0 any() and anyObject() are not anymore aliases ofthis method.

关于java - Mockito 的参数捕捉器行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48342795/

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