Reputation: 1669
I have a class with method:
class URAction {
public List<URules> getUrules(Cond cond, Cat cat) {
...
}
}
I want to create its mock:
@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
}
The problem is I can make the mock return uRules for only one argument:
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);
Not sure how to pass the second argument ie Cat in the when call above.
Any help would be greatly appreciated.
Thanks
Upvotes: 5
Views: 10213
Reputation: 1863
Could you try adding another argThat(argumentMatcher) for the second argument matcher?
Also, I find it's better to not have the anonymous class defined as a method and not inline as you have done. Then you could use it for verify() as well.
Your methods should look like this
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;
}
}
}
Then you could call your methods like this,
when(uraMock.getUrules(argThat(matcherOne(cond1)), argThat(matcherTwo(otherParam)))).thenReturn(uRules);
Then, as I you could call verify, to check if your when method really got called
verify(uraMock).getUrules(argThat(matcherOne(cond1)), argThat(matcherTwo(otherParam)));
If you don't care about the other param, you can do,
when(uraMock.getUrules(argThat(matcherOne(cond1)), argThat(any()))).thenReturn(uRules);
For more details see: http://site.mockito.org/mockito/docs/current/org/mockito/stubbing/Answer.html
Hope that's clear.. Good luck!
Upvotes: 4