Skip to content

Instantly share code, notes, and snippets.

@frnkst
Last active August 29, 2019 18:11
Show Gist options
  • Save frnkst/d3d58a23b896bdfdca0242c348cb02e3 to your computer and use it in GitHub Desktop.
Save frnkst/d3d58a23b896bdfdca0242c348cb02e3 to your computer and use it in GitHub Desktop.
Mockito Argument Matcher with Generics
import org.junit.Test;
import org.mockito.Matchers;
import org.mockito.Mockito;
import java.util.Arrays;
import java.util.List;
class SomeClass {
public String getResult(List param) {
return "real method called with a list";
}
}
public class MockTest {
@Test
public void testMock() {
SomeClass someClass = new SomeClass();
SomeClass mockedSomeClass = Mockito.mock(SomeClass.class);
System.out.println(someClass.getResult(Arrays.asList("test"))); // real method called with a list
System.out.println(someClass.getResult(Arrays.asList(new Integer(5)))); // real method called with a list
// 1. The implementation below works just fine. But isn't there a built in way?
// Mockito.when(mockedSomeClass.getResult(anyList())).thenAnswer(
// new Answer<String>(){
// @Override
// public String answer(InvocationOnMock invocation){
// List list = (List) invocation.getArguments()[0];
//
// if (list.get(0) instanceof String) {
// return ("mocked method called with a list of strings");
// }
//
// if (list.get(0) instanceof Integer) {
// return ("mocked method called with a list of integers");
// }
//
// return "";
// }});
// 2. Why does this not work as expected?
// https://stackoverflow.com/questions/22338536/mockito-return-value-based-on-property-of-a-parameter
//Mockito.when(mockedSomeClass.getResult(anyListOf(String.class))).thenReturn("mocked method called with a list of strings"); // mocked method called with a list of integers
//Mockito.when(mockedSomeClass.getResult(anyListOf(Integer.class))).thenReturn("mocked method called with a list of integers"); // mocked method called with a list of integers
// 3. Why does this not work as expected?
Mockito.when(mockedSomeClass.getResult(Matchers.<List<String>>anyList())).thenReturn("mocked method called with a list of strings"); // mocked method called with a list of integers
Mockito.when(mockedSomeClass.getResult(Matchers.<List<Integer>>anyList())).thenReturn("mocked method called with a list of integers"); // mocked method called with a list of integers
// 4. How to do it properly??
System.out.println(mockedSomeClass.getResult(Arrays.asList("test")));
System.out.println(mockedSomeClass.getResult(Arrays.asList(new Integer(5))));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment