7

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?

Amol Aggarwal
  • 2,674
  • 3
  • 24
  • 32

4 Answers4

11

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);
Jeff Bowman
  • 90,959
  • 16
  • 217
  • 251
3

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);
Stefan Birkner
  • 24,059
  • 12
  • 57
  • 72
1

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)
}
Noah Solomon
  • 1,251
  • 15
  • 23
-1

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.

gmaslowski
  • 774
  • 5
  • 13