如何使用Spring在单元测试中模拟远程REST API? [英] How to mock remote REST API in unit test with Spring?
问题描述
假设我在我的应用程序中创建了一个使用远程Web服务的简单客户端,该服务在某个URI / foo / bar / {baz}
中公开RESTful API。现在我希望对我调用此Web服务的客户端进行单元测试。
Assume I have made a simple client in my application that uses a remote web service that is exposing a RESTful API at some URI /foo/bar/{baz}
. Now I wish to unit test my client that makes calls to this web service.
理想情况下,在我的测试中,我想模仿我从网上获得的响应服务,给定特定请求,如 / foo / bar / 123
或 / foo / bar / 42
。我的客户端假设API实际上在某处运行,所以我需要一个本地Web服务来开始运行 http:// localhost:9090 / foo / bar
我的测试。
Ideally, in my tests, I’d like to mock the responses I get from the web service, given a specific request like /foo/bar/123
or /foo/bar/42
. My client assumes the API is actually running somewhere, so I need a local "web service" to start running on http://localhost:9090/foo/bar
for my tests.
我希望我的单元测试是自包含的,类似于使用Spring MVC Test框架测试Spring控制器。
I want my unit tests to be self-contained, similar to testing Spring controllers with the Spring MVC Test framework.
一个简单客户端的伪代码,从远程API获取数字:
Some pseudo-code for a simple client, fetching numbers from the remote API:
// Initialization logic involving setting up mocking of remote API at
// http://localhost:9090/foo/bar
@Autowired
NumberClient numberClient // calls the API at http://localhost:9090/foo/bar
@Test
public void getNumber42() {
onRequest(mockAPI.get("/foo/bar/42")).thenRespond("{ \"number\" : 42 }");
assertEquals(42, numberClient.getNumber(42));
}
// ..
我有什么选择使用Spring?
What are my alternatives using Spring?
推荐答案
如果使用Spring RestTemplate,则可以使用MockRestServiceServer。可以在此处找到一个示例 https://objectpartners.com/ 2013/01/09 / rest-client-testing-with-mockrestserviceserver /
If you use Spring RestTemplate you can use MockRestServiceServer. An example can be found here https://objectpartners.com/2013/01/09/rest-client-testing-with-mockrestserviceserver/
这篇关于如何使用Spring在单元测试中模拟远程REST API?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!