Java 如何编写一个不等于某物的匹配器
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/26067096/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to write a matcher that is not equal to something
提问by Churk
I am trying to create a mock for a call. Say I have this method I am trying to stub out:
我正在尝试为呼叫创建一个模拟。说我有这个方法,我想存根:
class ClassA {
public String getString(String a) {
return a + "hey";
}
}
What I am trying to mock out is: 1st instance is
我试图模拟的是:第一个实例是
when(classA.getString(eq("a")).thenReturn(...);`
in the same test case
在同一个测试用例中
when(classA.getString([anything that is not a])).thenReturn(somethingelse);
The 2nd case is my question: How do I match anyString()
other than "a"?
第二种情况是我的问题:我如何匹配anyString()
“a”以外的其他内容?
回答by John B
Use argThat
with Hamcrest:
argThat
与 Hamcrest 一起使用:
when(classA.getString(argThat(CoreMatchers.not(CoreMatchers.equalTo("a")))...
You might also be able to do this via ordering. If you put one when(anyString)
and when(eq("a"))
in the correct order, Mockito should test them in order and do the "a" logic when appropriate and then "anyString" logic otherwise.
您也可以通过订购来做到这一点。如果你把一个when(anyString)
并when(eq("a"))
以正确的顺序,应该的Mockito测试他们为了做“一”逻辑在适当的时候再“anyString”逻辑并非如此。
回答by troig
With Mockito
framework, you can use AdditionalMatchers
使用Mockito
框架,您可以使用AdditionalMatchers
ClassA classA = Mockito.mock(ClassA.class);
Mockito.when(classA.getString(Matchers.eq("a"))).thenReturn("something");
Mockito.when(classA.getString(AdditionalMatchers.not(Matchers.eq("a")))).thenReturn("something else");
Hope it helps.
希望能帮助到你。
回答by Churk
I actually took this approach after carefully looking at the suggested answers:
在仔细查看建议的答案后,我实际上采用了这种方法:
doAnswer(new Answer<String>() {
public String answer(InvocationOnMock invocation) throws Throwable {
String originalParam = (String) invocation.getArguments()[0];
return StringUtils.equalsIgnoreCase(originalParam, "a") ? "Something" : "Something Else";
}
}).when(classA).getString(anyString());
This allows me to handle more than just two cases by adjusting the return base on the params.
这允许我通过调整参数的返回基数来处理两种以上的情况。
回答by Pieter De Bie
In mockito the last stubbing is the most important. This means that you can simply use the standard matchers for your needs:
在 mockito 中,最后一个存根是最重要的。这意味着您可以简单地使用标准匹配器来满足您的需求:
// "Default" return values.
when(classA.getString(ArgumentMatchers.anyString())).thenReturn(somethingelse);
// Specific return value for "a"
when(classA.getString(ArgumentMatchers.eq("a"))).thenReturn(something);
Note that you haveto use ArgumentMatchers for both since you're mixing them.
请注意,您必须将 ArgumentMatchers 用于两者,因为您正在混合它们。