我有Sprint Boot集成测试与Wiremck,但由于某种原因,Wiremck不提供存根响应,超文本传输协议请求将发送到实际的外部api。我错过了什么吗?我可以从日志中看到Wiremck服务器在端口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;
}
}
我认为你混淆了运行在SpringBootTest中的两个不同服务器的信息。一方面,你告诉你的单元测试让你的实际Spring Boot应用程序在一个随机的web端口上运行测试,以模拟对你的webapp的真实调用。Spring应用程序分配的这个端口你正在拉入你的port
变量。
同时,您正在端口8888
上设置Wiremck,您也可以在日志中观察到如上所述。
在您的测试中,您现在通过返回"http://localhost:"port…
为您的测试调用已启动的Spring Boot应用程序的真实端口,该端口在您对RestTemplate实例的调用中被引用。
我认为您需要区分何时真正想要调用正在运行的Spring应用程序,以及何时使用wiremck进行外部endpoint模拟。
您为WireMock服务器存根了POST
方法,但随后您在TestRestTemplate
客户端中调用了GET
方法。
您也没有扩展路径变量{service-url-path}
。