首页 > 解决方案 > WireMock 未使用 Spring Boot 集成测试拦截 http 请求

问题描述

我使用 Wiremock 进行了 Sprint Boot Integration 测试,但由于某种原因,Wiremock 不提供存根响应,并且 http 请求将发送到实际的外部 api。我错过了什么吗?我可以从日志中看到 Wiremock 服务器正在端口 8888 上启动

   <dependency>
        <groupId>com.github.tomakehurst</groupId>
        <artifactId>wiremock-jre8-standalone</artifactId>
        <version>2.27.0</version>
        <scope>test</scope>
    </dependency>



@RunWith(SpringRunner.class)
@SpringBootTest(classes = GatewayApplication.class, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class RegTypeIntegratedTest {

    @LocalServerPort
    private int port;

    TestRestTemplate restTemplate = new TestRestTemplate();
    HttpHeaders headers = new HttpHeaders();
    ObjectMapper mapper = new ObjectMapper();

    @Rule
    public WireMockRule wireMockRule = new WireMockRule(options().port(8888));


    @Test
    public void testRegType()
            throws JSONException, JsonParseException, JsonMappingException, FileNotFoundException, IOException {

        wireMockRule.stubFor(post(urlPathMatching("{path}/.*/")).willReturn(
                aResponse().withHeader("Content-Type", "application/json").withBody(new String(Files.readAllBytes(
                        Paths.get("path/regtypeResponse_stub.json"))))));


        HttpEntity<String> entity = new HttpEntity<String>(null, headers);

        ResponseEntity<String> response = restTemplate.exchange(
                createURLWithPort("/{service-url-path}y/regTypes?regtype=I"), HttpMethod.GET, entity,
                String.class);

        String expected = new String(Files
                .readAllBytes(Paths.get("path/regtypeResponse_expected.json")));

        JSONAssert.assertEquals(expected, response.getBody(), true);
    }

    private String createURLWithPort(String uri) {
        return "http://localhost:" + port + uri;
    }
}

标签: spring-bootintegration-testingwiremock

解决方案


You stubbed for POST method for your WireMock server but then you're invoking a GET method in the TestRestTemplate client.

You're also not expanding your path variable {service-url-path}.


推荐阅读