尝试将 MockMvc 与 Wiremock 一起使用

5 java spring spring-boot wiremock

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

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

有人可以建议吗?


@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());
    }

}
Run Code Online (Sandbox Code Playgroud)

Dea*_*ool 3

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

另一种有用的方法是根本不启动服务器,而只测试其下面的层,其中 Spring 处理传入的 HTTP 请求并将其交给控制器。这样,几乎整个堆栈都被使用,并且您的代码将以与处理真实 HTTP 请求完全相同的方式被调用,但无需启动服务器的成本

所以MockMvc没有指向wiremockport(8070),它准确地说404。如果你想用wiremock进行测试,你可以HttpClients这里一样使用

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

或者您可以通过模拟来自控制器的任何服务调用来使用 Spring Boot Web 集成测试功能,如下所示