Reputation: 2824
My method interface is
Boolean isAuthenticated(String User)
I want to compare from list of values if any of the users are passed in the function from the list, then it should return true.
when(authService.isAuthenticated(or(eq("amol84"),eq("arpan"),eq("juhi")))).thenReturn(true);
I am using additional argument matcher 'or' but above code is not working. How can I resolve this issue?
Upvotes: 7
Views: 6757
Reputation: 95704
or
does not have a three-argument overload. (See docs.) If your code compiles, you may be importing a different or
method than org.mockito.AdditionalMatchers.or
.
or(or(eq("amol84"),eq("arpan")),eq("juhi"))
should work.
You might also try the oneOf
Hamcrest matcher (previously isOneOf
), accessed through the argThat
Mockito matcher:
when(authService.isAuthenticated(
argThat(is(oneOf("amol84", "arpan", "juhi")))))
.thenReturn(true);
Upvotes: 11
Reputation: 1261
If you're not interested in pulling in a library, you can iterate over all of the values you want to add to the mock:
// some collection of values
List<String> values = Arrays.asList("a", "b", "c");
// iterate the values
for (String value : values) {
// mock each value individually
when(authService.isAuthenticated(eq(value))).thenReturn(true)
}
Upvotes: 1
Reputation: 764
For me this works:
public class MockitoTest {
Mocked mocked = Mockito.mock(Mocked.class);
@Test
public void test() {
Mockito.when(mocked.doit(AdditionalMatchers.or(eq("1"), eq("2")))).thenReturn(true);
Assert.assertTrue(mocked.doit("1"));
Assert.assertTrue(mocked.doit("2"));
Assert.assertFalse(mocked.doit("3"));
}
}
interface Mocked {
boolean doit(String a);
}
Check if you're setting up mockito correctly, or if you're using the same Matchers as I do.
Upvotes: -1
Reputation: 24540
You could define separate answers:
when(authService.isAuthenticated(eq("amol84"))).thenReturn(true);
when(authService.isAuthenticated(eq("arpan"))).thenReturn(true);
when(authService.isAuthenticated(eq("juhi"))).thenReturn(true);
Upvotes: 3