gpt4 book ai didi

java - 如何让 Mockito 模拟按顺序执行不同的操作?

转载 作者:塔克拉玛干 更新时间:2023-11-03 03:34:31 25 4
gpt4 key购买 nike

以下代码:

  ObjectMapper mapper = Mockito.mock(ObjectMapper.class);
Mockito.doThrow(new IOException()).when(mapper).writeValue((OutputStream) Matchers.anyObject(), Matchers.anyObject());
Mockito.doNothing().when(mapper).writeValue((OutputStream) Matchers.anyObject(), Matchers.anyObject());

try {
mapper.writeValue(new ByteArrayOutputStream(), new Object());
} catch (Exception e) {
System.out.println("EXCEPTION");
}

try {
mapper.writeValue(new ByteArrayOutputStream(), new Object());
} catch (Exception e) {
System.out.println("EXCEPTION");
}

预期的输出是

EXCEPTION

对吗?

但我一无所获

如果我在 doNothing 之后进行 doThrow 操作

EXCEPTION
EXCEPTION

所以它看起来像是最后一个被采用的模拟......我认为它会按照它们注册的顺序采用模拟?

我希望生成一个模拟,第一次抛出异常并在第二次正常完成...

最佳答案

Mockito 可以用相同的参数对连续的行为进行 stub ——永远重复最后的指令——但它们都必须是同一个“链”的一部分。否则 Mockito 有效地认为您已经改变主意并覆盖您之前模拟的行为,如果您在 setUp 中建立了良好的默认值,这不是一个坏功能。或 @Before方法并希望在特定的测试用例中覆盖它们。

“接下来将发生哪个 Mockito 操作”的一般规则:将选择匹配所有参数的最近定义的链。在链中,每个 Action 都会发生一次(计算多个 thenReturn 值,如果给出像 thenReturn(1, 2, 3) ),然后最后一个 Action 将永远重复。

// doVerb syntax, for void methods and some spies
Mockito.doThrow(new IOException())
.doNothing()
.when(mapper).writeValue(
(OutputStream) Matchers.anyObject(), Matchers.anyObject());

这相当于链式 thenVerb更常见的语句when语法,你在这里为你的 void 正确地避免了它方法:

// when/thenVerb syntax, to mock methods with return values
when(mapper.writeValue(
(OutputStream) Matchers.anyObject(), Matchers.anyObject())
.thenThrow(new IOException())
.thenReturn(someValue);

请注意,您可以对 Mockito.doThrow 使用静态导入和 Matchers.* , 并切换到 any(OutputStream.class)而不是 (OutputStream) anyObject() ,并以此结束:

// doVerb syntax with static imports
doThrow(new IOException())
.doNothing()
.when(mapper).writeValue(any(OutputStream.class), anyObject());

参见 Mockito's documentation for Stubber获取您可以链接的命令的完整列表。

关于java - 如何让 Mockito 模拟按顺序执行不同的操作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20098607/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com