用外部Https主机进行Spring Boot测试的WireMock。

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

在我的应用程序中,我有外部的第三方API请求。我想通过模拟这个API请求来测试我的应用程序。

我的服务类。

String API_URL = "https://external.com/v1/%s";
public Result executeRequest(String apiVersion, String subUrl, HttpMethod httpMethod)
{
    try
    {
        HttpRequestBase httpRequest;
        String url = String.format(API_URL, subUrl);
        if (httpMethod.equals(HttpMethod.GET))
        {
            httpRequest = new HttpGet(url);
        }
        else if (httpMethod.equals(HttpMethod.POST))
        {
            httpRequest = new HttpPost(url);
            ((HttpPost) httpRequest).setEntity(new StringEntity(requestBody, "UTF-8"));
        }
        ...
        headers.forEach(httpRequest::setHeader);
        HttpResponse response = httpClient.execute(httpRequest);
    }
    catch (IOException e)
    {
        logger.error("IO Error: {}", e.getMessage());
        return handleExceptions(e);
    }
}

总结一下服务类,请求可以是get, post, delete, put. 而这些请求将被处理成头或主体部分。然后会被处理成http请求。

我的测试类。

@SpringBootTest
@ActiveProfiles("test")
@RunWith(SpringRunner.class)
public class ServiceTest
{

    private static final String API_URL = "https://external.com/v1";

    @Autowired
    private Service service;

    @Autowired
    protected Gson gson;

    @Rule
    public WireMockRule wireMockRule = new WireMockRule();

    @Test
    public void getResult_successfully()
    {
        Result result = new Result();
        wireMockRule.stubFor(get(urlPathMatching("/subUrl"))
                .willReturn(aResponse()
                        .proxiedFrom(API_URL)
                        .withStatus(200)
                        .withHeader("Content-Type", "application/json")
                        .withBody(gson.toJson(result))));

        Result returnResult = service.executeRequest("/subUrl", GET);

        assertThat(returnResult).isEqualTo(result);
    }
}

当我按照上面的方法实现的时候,嘲讽是行不通的。有什么建议吗?

注:我希望代码片断能让你了解代码的整体情况。

java spring-boot-test wiremock
1个回答
0
投票

我是这样解决的。

  1. 描述测试api-url和端口。因为Wiremock创建了嵌入式的localhost服务器,所以在applicaition-properties中,我解决了这样的问题;描述测试api-url和port。

所以在applicaition-properties中。

application-test.properties: 
  - service.url: http://localhost:8484
application-prod.properties: 
  - service.url: https://external.com/v1

然后我的测试类。

@ClassRule
public static WireMockRule wireMockRule = new WireMockRule(8484);

@Test
public void getResult_successfully()
{
    Result result = new Result();
    wireMockRule.stubFor(get(urlPathMatching("/subUrl"))
            .willReturn(aResponse()
                    .proxiedFrom(API_URL)
                    .withStatus(200)
                    .withHeader("Content-Type", "application/json")
                    .withBody(gson.toJson(result))));

    Result returnResult = service.executeRequest("/subUrl", GET);

    assertThat(returnResult).isEqualTo(result);
}
© www.soinside.com 2019 - 2024. All rights reserved.