Warm tip: This article is reproduced from stackoverflow.com, please click
java spring spring-boot wiremock

Trying to use MockMvc together with Wiremock

发布于 2020-04-21 11:16:53

I'm trying to make a mockMvc call run together with wiremock. But the mockMvc call below in the code keeps throwing 404 instead of the expected 200 HTTP status code.

I know that wiremock is running .. I can do http://localhost:8070/lala through browser when wiremock is running.

Can someone please advise ?


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

}
Questioner
snpst_tm_123
Viewed
13
Deadpool 2020-02-06 06:43

By default @SpringBootTest runs with a mocked environment and hence doesn't have a port assigned, 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

so MockMvc does not pointing to wiremockport (8070) which exactly says 404. If you want do test with wiremock you can use HttpClients like here

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

Or you can just use spring boot web integration test feature by mocking any service calling from controller like shown here