How do I return different results when calling the same mock method?
I
have a method that connects to another server and every time I call it, it returns different data.
I’m writing unit tests for the class that calls the method. I mocked the class, and I wanted it to return the stub result. It can actually use doReturn
, but it returns the same data every time. I want it to return different data, and I want to be able to specify what it should be.
I
tried using “doReturn – when” and it works, but I can’t get it to return a different result. I don’t know how to do it.
I also tried using “when-thenReturn”, which is the solution I found on StackOverflow. With it, I can specify a different response each time the same method is called.
The problem is that I get a compile error
The method XXX is undefined for the type
OngoingStubbing<MyClass>
JSONArray jsonArray1 = { json array1 here };
JSONArray jsonArray2 = { json array2 here };
Works but return the same jsonArray1 every time:
MyClass MyClassMock = mock(MyClass.class);
Mockito.doReturn(jsonArray1)
.when(MyClassMock).getMyValues(any(List.class), any (String.class), any(String.class),
any(String.class),
any(String.class));
Does not work:
when(MyClassMock).getMyValues(any(List.class),
any(String.class), any(String.class),
any(String.class),
any(String.class)).thenReturn(jsonArray1, jsonArray2);
Compile error:
The method getMyValues(any(List.class), any(String.class), any (String.class), any(String.class), any(String.class)) is undefined for the type OngoingStubbing<MyClass>
Compilation error:
The method getMyValues(any(List.class), any(String.class),
any(String.class), any(String.class), any(String.class)) is undefined
for the type OngoingStubbing
Solution
Make sure to put the simulation and its methods in when
:
when(MyClassMock.getMyValues(any(List.class),
any(String.class), any(String.class),
any(String.class),
any(String.class))
.thenReturn(jsonArray1)
.thenReturn(jsonArray2);