当构造RestTemplate时无法控制时,如何在春季模拟Rest调用的响应 [英] How to mock response of Rest call in spring when you can't controll when the RestTemplate is constructed

查看:266
本文介绍了当构造RestTemplate时无法控制时,如何在春季模拟Rest调用的响应的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用MockRestServiceServer为rest方法编写一个集成级别测试.我的rest方法是代理,它最终通过静态帮助器方法创建restTemplate并将请求代理到第三方.我想嘲笑那个第三方.实际上,对具有不同配置的不同方进行了两次不同的休息呼叫以服务该请求.

I want to write an integration level test for a rest method using MockRestServiceServer. My rest method is a proxy, it ends up creating a restTemplate via a static helper method and proxys the request to a third party. I want to mock out that third party. Actually two different rest calls are made to different parties with different configurations to service the request.

我想使用MockRestServiceServer,但是它希望我传入在集成测试中构建的restTemplate.我可以尝试使用模拟来确保使用我自己的restTemplate,但是现在我必须引入4个新的maven包并编写一些代码来安全地进行注入,并确保为这两个使用不同的restTemplate我的代理服务器调用了不同的外部服务.这还需要我对我的代码有所了解,从而使集成测试比我更喜欢黑盒子.

I want to use MockRestServiceServer, but it expects me to pass in the restTemplate, which is constructed within my integration test. I can try to use mocks to ensure that my own restTemplate is used, but now I have to pull in 4 new maven packages and write a bit of code to do the inject safely, and make sure that a different restTemplate is used for the two different external service calls my proxy does. It also requires me to know a little bit about my code and thus makes my integration test less of a black box then I would prefer.

是否有更干净的方法来模拟服务?我知道我的方法可以奏效,但是感觉太麻烦了.有没有一种方法可以模拟这种情况而不必提前注入RestTemplate?

Is there a cleaner way to mock the services? I know my approach could work, but it's just feeling overly cumbersome. Is there a way to mock this without having to inject the RestTemplate ahead of time?

推荐答案

如果不想重新设计用于创建RestTemplate实例的部分,则可以参数化外部服务的地址并使用来模拟整个外部服务Wiremock之类的工具.

If you don't want to redesign the part where you create instances of RestTemplate then you can parametrize out address of the external service and mock the entire external service using tools like Wiremock.

实际上,使用Wiremock,您可以在特定端口上运行嵌入式HTTP Server.您还可以告诉Wiremock在发出预定义的请求时返回指定的响应.它基本上只是一个模拟,但是通过HTTP.

Using Wiremock, you actually run an embedded HTTP Server on a specific port. You can also tell Wiremock to return specified response when predefined request is made. It basically is just a mock, but over HTTP.

这样,您将获得良好的集成测试,该测试不仅可以测试典型的Java代码,而且还可以测试整个通信(例如JSON(反)序列化).我在工作中广泛使用Wiremock(及相关工具),它们的工作确实很吸引人.

This way you would get a good integration test that would not only test your typical Java code but also entire communication (like JSON (de)serialization). I use Wiremock (and related) extensively at work and they do work like a charm.

这篇关于当构造RestTemplate时无法控制时,如何在春季模拟Rest调用的响应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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