模拟第一次调用失败,第二次调用成功 [英] Simulate first call fails, second call succeeds

查看:56
本文介绍了模拟第一次调用失败,第二次调用成功的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想用 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");

这篇关于模拟第一次调用失败,第二次调用成功的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆