如何告诉Mockito模拟对象在下一次被调用时返回不同的东西?

所以,我创build一个模拟对象作为类级别的静态variables像这样…在一个testing中,我希望Foo.someMethod()返回一个特定的值,而在另一个testing中,我希望它返回一个不同的价值。 我遇到的问题是,似乎我需要重build模拟,以使其正常工作。 我想避免重build模拟,并在每个testing中使用相同的对象。

 class TestClass { private static Foo mockFoo; @BeforeClass public static void setUp() { mockFoo = mock(Foo.class); } @Test public void test1() { when(mockFoo.someMethod()).thenReturn(0); TestObject testObj = new TestObject(mockFoo); testObj.bar(); // calls mockFoo.someMethod(), receiving 0 as the value } @Test public void test2() { when(mockFoo.someMethod()).thenReturn(1); TestObject testObj = new TestObject(mockFoo); testObj.bar(); // calls mockFoo.someMethod(), STILL receiving 0 as the value, instead of expected 1. } } 

在第二个testing中,当我调用testObj.bar()的时候,我仍然收到0的值…解决这个问题的最好方法是什么? 请注意,我知道我可以在每个testing中使用不同的Foo模拟,但是,我必须从mockFoo链接多个请求,这意味着我必须在每个testing中进行链接。

首先不要模拟静态。 把它变成一个私人领域。 只要把你的setUp类放在@Before而不是@BeforeClass 。 它可能会运行一堆,但它很便宜。

其次,你现在的方式是获得一个模拟回报不同的testing的正确方法。

您也可以连续调用存根 (2.8.9 api中的#10)。 在这种情况下,您可以使用多个返回呼叫,或者使用多个参数返回呼叫(可变参数)。

 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 } }