Home > front end >  How can MockMvc get around API exceptions?
How can MockMvc get around API exceptions?

Time:03-06

Ideally, I want this:

    @Test
    void testWelcome() throws Exception {
        mockMvc.perform(get("/oups"))
            .andExpect(status().isInternalServerError());
    }

But the test fails because it throws at get("/oops") (which runs a controller method that throws a RuntimeException) before it can get to the assertion. How do I deal with this issue? This is my quick fix for now:

    @Test
    void testTriggerException() throws Exception {
        try {
            mockMvc.perform(get("/oops"))
            .andExpect(status().isInternalServerError());
        } catch (Exception e) {
            return;
        }
        fail();
    }

CodePudding user response:

You can try this:

Assertions
    .assertThatThrownBy(
                    () -> mockMvc.perform(get("/oops").contentType(MediaType.APPLICATION_JSON)))
    .hasCauseInstanceOf(RuntimeException.class)
    .hasMessageContaining("The exception message");
  • Related