如何在内部API集成测试中模拟调用外部API的响应。

问题描述 投票:1回答:1

我正在为一个应用程序编写集成测试,该应用程序使用内部REST API来执行一个动作;全部都是Java。在API中,有一个调用外部API的POST方法。在测试中,我需要向我的API发送一个请求来执行一个动作。问题是,我不想在运行集成测试时向外部API发送真实的请求。我怎样才能模拟外部API调用的响应? 有没有一种方法,我仍然可以在我的测试中向我的API发送POST请求(嘲讽或其他),但对Java POST方法中执行的外部调用使用嘲讽的响应?

java api testing mockito integration
1个回答
0
投票

我的做法如下:创建一个服务层,让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);
    }

希望能帮到你

© www.soinside.com 2019 - 2024. All rights reserved.