I have a method call that needs to return valueA the first time it is called and valueB the second time it is called. I'm using a PowerMockito spy, so if I were just needing to return one value it would look like this:
PowerMockito.doReturn(valueA).when(mockedObject, "methodName");
It looks like I can do chained returns like this:
PowerMockito.when(mockedObject, "methodName").thenReturn(valueA).thenReturn(valueB);
But I need to indicate chained returns with doReturn so that the real methodName() isn't called on my Spy.
I've tried this, but Eclipse gives me an error saying that it won't even compile:
PowerMockito.doReturn(valueA).doReturn(valueB).when(mockedObject, "methodName");
Is it even possible to chain returns with doReturn and powermockito? If so, how?
I don't think so. Rather, You can achieve it with using doAnswer and Queue like below
@Test
public void testReturnChain() throws Exception {
Example example = new Example() {
public String getValue() {
return null;
}
};
Example mockExample = spy(example);
PowerMockito.doAnswer(new Answer<String>() {
private final Queue<String> values = new LinkedList<String>(Arrays.asList("firstValue", "secondValue"));
public String answer(InvocationOnMock invocationOnMock) throws Throwable {
return values.poll();
}
}).when(mockExample, "getValue");
System.out.println(mockExample.getValue());
System.out.println(mockExample.getValue());
System.out.println(mockExample.getValue());
}