博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
mockito 多层调用_连续调用的Mockito迭代器样式存根
阅读量:2539 次
发布时间:2019-05-11

本文共 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*方法链,以在指定迭代器样式存根。

Mockito存根连续呼叫 (Mockito Stubbing Consecutive Calls)

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.

在我们要模拟同一方法的多次执行中的不同响应的情况下,这很有用。 请注意,如果我们定义了多个使用相同参数进行存根的方法,则最后一个将覆盖较早的方法。

Mockito迭代器方法存根 (Mockito Iterator Methods Stubbing)

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.

我们可以使用这种方法对迭代器进行存根。 让我们看一个通过连续调用对迭代器方法进行存根的简单示例。

Iterator
mockIter = 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示例。

翻译自:

mockito 多层调用

转载地址:http://xyqzd.baihongyu.com/

你可能感兴趣的文章
vue-cli3创建项目时报错
查看>>
输入1-53周,输出1-53周的开始时间和结束时间
查看>>
实验二
查看>>
shell——按指定列排序
查看>>
crash 收集
查看>>
507 LOJ 「LibreOJ NOI Round #1」接竹竿
查看>>
UI基础--烟花动画
查看>>
2018. 2.4 Java中集合嵌套集合的练习
查看>>
精通ASP.NET Web程序测试
查看>>
vue 根据不同属性 设置背景
查看>>
51Nod1601 完全图的最小生成树计数 Trie Prufer编码
查看>>
Codeforces 1110D. Jongmah 动态规划
查看>>
android驱动在win10系统上安装的心酸历程
查看>>
优雅的程序员
查看>>
oracle之三 自动任务调度
查看>>
Android dex分包方案
查看>>
ThreadLocal为什么要用WeakReference
查看>>
删除本地文件
查看>>
FOC实现概述
查看>>
base64编码的图片字节流存入html页面中的显示
查看>>