我已按如下方式完成此操作:创建一个服务层,使 API 调用外部服务。我在 Spring 的 RestTemplate 上构建了我的,但您可以使用任何库进行调用。所以它会有 get() 或 post() 之类的方法。
然后我使用 Postman 对外部 API 执行一些请求,并将响应保存在文件中,并将这些文件添加到我的项目中。
最后,在我的测试中,我模拟了对我的小 API 服务层的调用,这样它就不会转到外部 API,而是从我之前保存的测试文件中读取。这将使用来自外部 API 的已知有效负载运行被测代码,但在测试期间不需要连接到它,并且在我自己更新文件中的响应之前不会改变。
我使用 EasyMock,但任何模拟库都可以使用。下面是一个测试的例子。
@Test
public void test_addPhoneToExternalService() {
// Mock my real API service.
ApiService mockApiService = EasyMock.createMock(ApiService.class);
// Construct my service under test using my mock instead of the real one.
ServiceUnderTest serviceUnderTest = new ServiceUnderTest(mockApiService);
// Expect the body of the POST request to look like this.
Map<String, Object> requestBody = new HashMap<String, Object>() {{
put("lists", 0);
put("phone", "800-555-1212");
put("firstName", "firstName");
put("lastName", "lastName");
}};
// Read the response that I manually saved as json.
JsonNode expectedResponse = Utils.readJson("response.json");
expect(mockApiService.post(anyObject(),
eq("https://rest.someservice.com/api/contacts"), eq(serialize(requestBody))))
.andReturn(expectedResponse);
EasyMock.replay(mockApiService);
// Call the code under test. It ingests the response
// provided by the API service, which is now mocked,
// and performs some operations, then returns a value
// based on what the response contained (for example,
// "{\"id\":42}").
long id = serviceUnderTest.addPhone("firstName", "lastName", "800-555-1212");
Assert.assertThat(id, is(42L));
EasyMock.verify(mockApiService);
}
希望有帮助!