gpt4 book ai didi

java - 尝试将 MockMvc 与 Wiremock 一起使用

转载 作者:行者123 更新时间:2023-12-05 06:21:09 25 4
gpt4 key购买 nike

我正在尝试使 mockMvc 调用与 wiremock 一起运行。但是下面代码中的 mockMvc 调用一直抛出 404 而不是预期的 200 HTTP 状态代码。

我知道 wiremock 正在运行..我可以做 http://localhost:8070/lala在 wiremock 运行时通过浏览器。

有人可以建议吗?


@RunWith(SpringRunner.class)
@SpringBootTest(classes = TestApp.class)
@AutoConfigureMockMvc
public class MyControllerTest {


@Inject
public MockMvc mockMvc;

@ClassRule
public static final WireMockClassRule wireMockRule = new WireMockClassRule(8070);

@Rule
public WireMockClassRule instanceRule = wireMockRule;

public ResponseDefinitionBuilder responseBuilder(HttpStatus httpStatus) {
return aResponse()
.withStatus(httpStatus.value());
}

@Test
public void testOne() throws Exception {
stubFor(WireMock
.request(HttpMethod.GET.name(), urlPathMatching("/lala"))
.willReturn(responseBuilder(HttpStatus.OK)));

Thread.sleep(1000000);

mockMvc.perform(MockMvcRequestBuilders.request(HttpMethod.GET, "/lala")) .andExpect(status().isOk());
}

}

最佳答案

默认情况下 @SpringBootTest 在模拟环境中运行,因此没有分配端口,docs

Another useful approach is to not start the server at all but to test only the layer below that, where Spring handles the incoming HTTP request and hands it off to your controller. That way, almost of the full stack is used, and your code will be called in exactly the same way as if it were processing a real HTTP request but without the cost of starting the server

所以 MockMvc 没有指向 wiremockport (8070),它恰好表示 404。如果你想用 wiremock 做测试,你可以使用 HttpClients like here

CloseableHttpClient httpClient = HttpClients.createDefault();
HttpGet request = new HttpGet("http://localhost:8070/lala");
HttpResponse httpResponse = httpClient.execute(request);

或者您可以通过模拟来自 Controller 的任何服务调用来使用 spring boot web 集成测试功能,如所示 here

关于java - 尝试将 MockMvc 与 Wiremock 一起使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60084777/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com