多次尝试模拟或模拟 HttpResponse

发布于 2025-01-14 23:54:13 字数 257 浏览 2 评论 0原文

我想对可能返回 HTTP 状态代码 (SERVICE_UNAVAILABLE) 的服务进行 JUnit 测试。对我来说,由于容器已扩大且尚未可达,因此这可能不可用。在这种情况下,我会让代码重试服务最多 3 次。

我可以模拟 HttpResponse 进行测试,但仅限于一种情况。 Mockito 是否可以创建一个模拟对象,在第一次尝试时返回一个内容,跟踪尝试次数并根据尝试次数返回不同的结果?我唯一能想到做的就是实现我自己的 HttpResponse。 Mockito 有更好的方法吗?

I'd like to do a JUnit test for a service that could return an HTTP status code (SERVICE_UNAVAILABLE). For me, this could be unavailable due to the container being scaled up and not yet reachable. In that case, I'm having the code retry the service up to 3 times.

I can mock an HttpResponse for testing, but only for one situation. Can Mockito create a mocked object that returns one thing on the first attempt, track the number of attempts and return a different result depending on the attempt number? The only thing I can think of doing is to implement my own HttpResponse. Is there a better approach with Mockito?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

等待圉鍢 2025-01-21 23:54:13

存根连续调用(迭代器式存根)

https://www.javadoc.io/doc/org.mockito/mockito-core/latest/org/mockito/Mockito.html#10

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"));

 //Any consecutive call: prints "foo" as well (last stubbing wins).
 System.out.println(mock.someMethod("some arg"));

Stubbing consecutive calls (iterator-style stubbing)

https://www.javadoc.io/doc/org.mockito/mockito-core/latest/org/mockito/Mockito.html#10

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"));

 //Any consecutive call: prints "foo" as well (last stubbing wins).
 System.out.println(mock.someMethod("some arg"));
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文