gpt4 book ai didi

java - 具有多个参数的 Mockito 参数匹配器

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

我有一个带有方法的类:

class URAction {
public List<URules> getUrules(Cond cond, Cat cat) {
...
}
}

我想创建它的模拟:

@Mock
URAction uraMock;

@Test
public void testSth() {
Cond cond1;
Cat cat1;
List<URule> uRules;

// pseudo code
// when uraMock's getUrules is called with cond1 and cat1
// then return uRules
}

问题是我可以让模拟只为一个参数返回 uRules:

 when(uraMock.getUrules(argThat(
new ArgumentMatcher<Cond> () {

@Override
public boolean matches(Object argument) {
Cond cond = ((Cond) argument);
if (cond.getConditionKey().equals(cond1.getConditionKey())
return true;
return false;
}

}
))).thenReturn(uRules);

不确定如何在上面的 when 调用中传递第二个参数,即 Cat。

如有任何帮助,我们将不胜感激。

谢谢

最佳答案

您可以尝试为第二个参数匹配器添加另一个 argThat(argumentMatcher) 吗?

此外,我发现最好不要将匿名类定义为方法,也不要像您所做的那样内联。然后您也可以将它用于 verify()。

你的方法应该是这样的

ArgumentMatcher<Cond> matcherOne(Cond cond1){
return new ArgumentMatcher<Cond> () {
@Override
public boolean matches(Object argument) {
Cond cond = ((Cond) argument);
if (cond.getConditionKey().equals(cond1.getConditionKey())
return true;
return false;
}
}
}

ArgumentMatcher<OtherParam> matcherTwo(OtherParam otherParam){
return new ArgumentMatcher<OtherParam> () {
@Override
public boolean matches(Object argument) {
OtherParam otherParam = ((OtherParam) argument);
if (<some logic>)
return true;
return false;
}
}
}

然后你可以像这样调用你的方法,

when(uraMock.getUrules(argThat(matcherOne(cond1)), argThat(matcherTwo(otherParam)))).thenReturn(uRules);

然后,正如我所说,您可以调用 verify , 检查你的 when 方法是否真的被调用了

verify(uraMock).getUrules(argThat(matcherOne(cond1)), argThat(matcherTwo(otherParam)));

如果你不关心其他参数,你可以这样做,

when(uraMock.getUrules(argThat(matcherOne(cond1)), argThat(any()))).thenReturn(uRules);

有关详细信息,请参阅:http://site.mockito.org/mockito/docs/current/org/mockito/stubbing/Answer.html

希望这是清楚的..祝你好运!

关于java - 具有多个参数的 Mockito 参数匹配器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40372421/

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