Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

mockito -using one of the values from list of values to compare in matcher

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?

like image 299
Amol Aggarwal Avatar asked Apr 21 '16 14:04

Amol Aggarwal


3 Answers

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 isOneOf Hamcrest matcher, accessed through the argThat Mockito matcher:

when(authService.isAuthenticated(argThat(isOneOf("amol84", "arpan", "juhi"))))
    .thenReturn(true);
like image 109
Jeff Bowman Avatar answered Nov 17 '22 17:11

Jeff Bowman


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);
like image 3
Stefan Birkner Avatar answered Nov 17 '22 17:11

Stefan Birkner


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)
}
like image 1
Noah Solomon Avatar answered Nov 17 '22 16:11

Noah Solomon