【问题标题】:Trying to use MockMvc together with Wiremock尝试将 MockMvc 与 Wiremock 一起使用
【发布时间】:2020-02-05 22:03:39
【问题描述】:

我正在尝试让 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());
    }

}

【问题讨论】:

  • 我已经更新了帖子中的代码以显示完整的测试类。

标签: java spring spring-boot wiremock


【解决方案1】:

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

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

所以MockMvc 没有指向确切地说404 的wiremockport (8070)。如果你想用wiremock进行测试,你可以使用HttpClients,比如here

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-06-08
    • 2016-03-25
    • 2013-12-25
    • 2014-09-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多