我有一个带有方法的类:
class URAction {
public List<URules> getUrules(Cond cond, Cat cat) {
...
}
}
Run Code Online (Sandbox Code Playgroud)
我想创建它的模拟:
@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
}
Run Code Online (Sandbox Code Playgroud)
问题是我可以让模拟返回 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);
Run Code Online (Sandbox Code Playgroud)
不确定如何在上面的 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;
}
}
}
Run Code Online (Sandbox Code Playgroud)
然后你可以这样调用你的方法,
when(uraMock.getUrules(argThat(matcherOne(cond1)), argThat(matcherTwo(otherParam)))).thenReturn(uRules);
Run Code Online (Sandbox Code Playgroud)
然后,就像我一样,您可以调用verify来检查您的 when 方法是否真的被调用
verify(uraMock).getUrules(argThat(matcherOne(cond1)), argThat(matcherTwo(otherParam)));
Run Code Online (Sandbox Code Playgroud)
如果你不关心其他参数,你可以这样做,
when(uraMock.getUrules(argThat(matcherOne(cond1)), argThat(any()))).thenReturn(uRules);
Run Code Online (Sandbox Code Playgroud)
有关更多详细信息,请参阅:http://site.mockito.org/mockito/docs/current/org/mockito/stubbing/Answer.html
希望这是清楚的..祝你好运!
| 归档时间: |
|
| 查看次数: |
6870 次 |
| 最近记录: |