How to tell a Mockito mock object to return something different the next time it is called?
You could also Stub Consecutive Calls (#10 in 2.8.9 api). In this case, you would use multiple thenReturn calls or one thenReturn call with multiple parameters (varargs).
import static org.junit.Assert.assertEquals;import static org.mockito.Mockito.mock;import static org.mockito.Mockito.when;import org.junit.Before;import org.junit.Test;public class TestClass { private Foo mockFoo; @Before public void setup() { setupFoo(); } @Test public void testFoo() { TestObject testObj = new TestObject(mockFoo); assertEquals(0, testObj.bar()); assertEquals(1, testObj.bar()); assertEquals(-1, testObj.bar()); assertEquals(-1, testObj.bar()); } private void setupFoo() { mockFoo = mock(Foo.class); when(mockFoo.someMethod()) .thenReturn(0) .thenReturn(1) .thenReturn(-1); //any subsequent call will return -1 // Or a bit shorter with varargs: when(mockFoo.someMethod()) .thenReturn(0, 1, -1); //any subsequent call will return -1 }}
For all who search to return something and then for another call throw exception:
when(mockFoo.someMethod()) .thenReturn(obj1) .thenReturn(obj2) .thenThrow(new RuntimeException("Fail"));
or
when(mockFoo.someMethod()) .thenReturn(obj1, obj2) .thenThrow(new RuntimeException("Fail"));
First of all don't make the mock static. Make it a private field. Just put your setUp class in the @Before
not @BeforeClass
. It might be run a bunch, but it's cheap.
Secondly, the way you have it right now is the correct way to get a mock to return something different depending on the test.