gpt4 book ai didi

java - 我可以混合使用 Argument Captor 和常规匹配器吗?

转载 作者:搜寻专家 更新时间:2023-10-30 21:39:28 24 4
gpt4 key购买 nike

我需要在 Mockito 中验证一个具有多个参数的方法,但只需要捕获一个参数,其他我只需要一个简单的匹配器。这可能吗?

例如,如果我有:

@Mock
private Map<K,V> mockedMap;
...
ArgumentCaptor<K> argument = ArgumentCaptor.forClass(K.class);
verify(mockedMap).put(argument.capture(), any(V.class));

在这种情况下,尽管我只需要捕获第一个参数,但我是否需要为每个参数编写一个捕获器?

最佳答案

In this case do I need to write a captor for each argument in spite of the fact I need to capture only the first argument?

durron597's answer是正确的——如果您想捕获其中一个参数,则不需要捕获所有参数。不过有一点需要澄清:调用 ArgumentCaptor.capture()算作 Mockito 匹配器,在 Mockito 中,如果您对任何方法参数使用 匹配器 you do have to use a matcher for all arguments .

对于一个方法yourMock.yourMethod(int, int, int)和一个 ArgumentCaptor<Integer> intCaptor :

/*  good: */  verify(yourMock).yourMethod(2, 3, 4);  // eq by default
/* same: */ verify(yourMock).yourMethod(eq(2), eq(3), eq(4));

/* BAD: */ verify(yourMock).yourMethod(intCaptor.capture(), 3, 4);
/* fixed: */ verify(yourMock).yourMethod(intCaptor.capture(), eq(3), eq(4));

这些也有效:

verify(yourMock).yourMethod(intCaptor.capture(), eq(5), otherIntCaptor.capture());
verify(yourMock).yourMethod(intCaptor.capture(), anyInt(), gt(9000));

关于java - 我可以混合使用 Argument Captor 和常规匹配器吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32716763/

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