spring-boot - 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;
}
}
解决方案
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}
.
推荐阅读
- python - 打开 Django InMemoryUploadedFile 会导致 I/O 操作错误?
- c - 在 C 中输入字母之前要求输入数字的程序
- python - 套接字侦听()接受一个太多的连接
- php - 从存储下载文档时出现问题,存储:链接不起作用 laravel 6
- tensorflow - 如何解析 tfds.features.Sequence 对象?它与 tf.io.FixedLenSequenceFeature 不兼容
- javascript - 表单提交按钮中的表单同时触发
- javascript - 如何将表格行数据添加到数组
- odata - 我可以在“ZGWSAMPLE_BASIC”odata 服务中创建的表中插入数据吗?
- python - 从分钟值在熊猫数据框中添加日期时间列
- javascript - WooCommerce Checkout - 如果选中复选框,则需要输入