本文共 2253 字,大约阅读时间需要 7 分钟。
mockito 多层调用
Sometimes we want to mock different responses for the consecutive calls on the same method. We can create then*
methods chain with when()
to specify iterator style stubbing in .
有时,我们想对同一方法的连续调用模拟不同的响应。 我们可以使用when()
创建then*
方法链,以在指定迭代器样式存根。
Let’s look at a simple example of and return a response when a method is called with same parameters. We will use assertions to verify the stubbed methods.
让我们看一个的简单示例,并在使用相同参数调用方法时返回响应。 我们将使用断言来验证存根方法。
UpdateUtils mockUU = mock(UpdateUtils.class); when(mockUU.update("Data")) .thenThrow(new RuntimeException()) .thenReturn("DATA"); assertThrows(RuntimeException.class, () -> mockUU.update("Data"));assertEquals("DATA", mockUU.update("Data"));//further calls will return the last mocked outputassertEquals("DATA", mockUU.update("Data"));
Notice that once the mocking chain reaches the end, further calls will return the last mocked response.
注意,一旦模拟链到达末尾,进一步的调用将返回最后的模拟响应。
We can also provide different responses in the thenReturn()
method through varargs.
我们还可以通过varargs在thenReturn()
方法中提供不同的响应。
when(mockUU.update("Emp")).thenReturn("EMP", "EMPLOYEE", "EMP1");assertEquals("EMP", mockUU.update("Emp"));assertEquals("EMPLOYEE", mockUU.update("Emp"));assertEquals("EMP1", mockUU.update("Emp"));assertEquals("EMP1", mockUU.update("Emp"));
This is useful in the cases where we want to mock different response in multiple executions of the same method. Note that if we define multiple methods stubbing with same arguments, then the last one will override the earlier ones.
在我们要模拟同一方法的多次执行中的不同响应的情况下,这很有用。 请注意,如果我们定义了多个使用相同参数进行存根的方法,则最后一个将覆盖较早的方法。
We can use this approach to stub an Iterator. Let’s have a look at a simple example of stubbing iterator methods through consecutive calls.
我们可以使用这种方法对迭代器进行存根。 让我们看一个通过连续调用对迭代器方法进行存根的简单示例。
IteratormockIter = mock(Iterator.class);when(mockIter.hasNext()).thenReturn(true, true, true, false);int[] values = new int[] {1,2,3,4};when(mockIter.next()).thenReturn(values[0], values[1], values[2], values[3]);int index = 0;while(mockIter.hasNext()) { assertTrue(values[index] == mockIter.next()); index++;}
翻译自:
mockito 多层调用
转载地址:http://xyqzd.baihongyu.com/