模拟第一次调用失败,第二次调用成功

编程入门 行业动态 更新时间:2024-10-11 09:27:28
本文介绍了模拟第一次调用失败,第二次调用成功的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我想用 Mockito 来测试下面的(简化的)代码.我不知道如何告诉 Mockito 第一次失败,然后第二次成功.

I want to use Mockito to test the (simplified) code below. I don't know how to tell Mockito to fail the first time, then succeed the second time.

for(int i = 1; i < 3; i++) { String ret = myMock.doTheCall(); if("Success".equals(ret)) { log.write("success"); } else if ( i < 3 ) { log.write("failed, but I'll try again. attempt: " + i); } else { throw new FailedThreeTimesException(); } }

我可以设置成功测试:

Mockito.when(myMock).doTheCall().thenReturn("Success");

和失败测试:

Mockito.when(myMock).doTheCall().thenReturn("you failed");

但是我如何测试它是否失败了一次(或两次)然后成功了,这很好吗?

But how can I test that if it fails once (or twice) then succeeds, it's fine?

推荐答案

来自 文档:

有时我们需要为相同的方法调用使用不同的返回值/异常进行存根.典型的用例可能是模拟迭代器.Mockito 的原始版本没有这个功能来促进简单的模拟.例如,可以使用 Iterable 或简单的集合来代替迭代器.这些提供了自然的存根方式(例如使用真实的集合).不过,在极少数情况下,存根连续调用可能会很有用:

Sometimes we need to stub with different return value/exception for the same method call. Typical use case could be mocking iterators. Original version of Mockito did not have this feature to promote simple mocking. For example, instead of iterators one could use Iterable or simply collections. Those offer natural ways of stubbing (e.g. using real collections). In rare scenarios stubbing consecutive calls could be useful, though: when(mock.someMethod("some arg")) .thenThrow(new RuntimeException()) .thenReturn("foo"); //First call: throws runtime exception: mock.someMethod("some arg"); //Second call: prints "foo" System.out.println(mock.someMethod("some arg"));

所以在你的情况下,你会想要:

So in your case, you'd want:

when(myMock.doTheCall()) .thenReturn("You failed") .thenReturn("Success");

更多推荐

模拟第一次调用失败,第二次调用成功

本文发布于:2023-11-23 04:25:04,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1620080.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!