简体   繁体   中英

How can I realistically test the server response of a controller that has a null pointer exception

I want to write a test that evaluates the response of a controller that has a NullPointerException while handling the request.

For that purpose I wrote a controller that throws a NullPointer while handling the request. Using the MockMVC controller I send a GET request to that controller.

The controller that throws the Null Pointer while handling it:

@Controller
public class Controller{  

    @GetMapping(value = "/api/data")
    @ResponseBody
    public ResponseEntity<Resource> getData() {

        if (true)
            throw new NullPointerException(); // Intended Nullpointer Exception 

        return ResponseEntity.notFound().build();
    }
}

The test function that I expect to receive a 500 error:

@RunWith(SpringRunner.class)
@SpringBootTest
@AutoConfigureMockMvc

public class Test {

    @Autowired
    protected MockMvc mockMvc;

    @Test
    public void shouldReturn500StatusWhenControllerThrowsAnException() throws Exception {
        MvcResult result = this.mockMvc.perform(get("/api/data"))
            .andExpect(status().is5xxServerError())
            .andReturn();
    }

}

I expect the MockMVC request to return an error 500, like the real controller does when it runs as server. Actually instead the MockMVC just fails with a NullPointer Exception, and does not return anything.

EDIT after more information have been added to the original question: I had the same issue, try with these annotations instead of the three you have:

@RunWith(SpringRunner.class)
@WebMvcTest
@AutoConfigureWebClient

I found a solution that works for me using WebTestClient.

Added two new dependencies to my build.gradle:

testCompile "org.springframework.boot:spring-boot-starter-webflux:2.1.3.RELEASE"
testCompile "org.springframework.boot:spring-boot-starter-test:2.1.3.RELEASE"

The test function looks like that:

@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class Test {

    @Autowired
    private WebTestClient webTestClient;

    @Test
    public void shouldReturn500StatusWhenControllerThrowsAnException() throws Exception {

        webTestClient.get().uri("/api/data")
            .exchange()
            .expectStatus().is5xxServerError();

    }

}

Like that the GET request returns the error 500 exactly how it does in real world conditions.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM