【发布时间】:2020-11-19 12:58:15
【问题描述】:
我使用 Wiremock 进行了 Sprint Boot 集成测试,但由于某种原因,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;
}
}
【问题讨论】:
-
我认为这是使用 HTTP 方法的一些疏忽的情况,但现在我和 cobz 一样困惑。你能解释一下为什么需要 WireMock 和 Spring Boot 服务器吗?
标签: spring-boot integration-testing wiremock