Search code examples
springkotlinjunitcontrollerrest

How can I test my controller for throwing an exception in Kotlin?


So I have a controller with one GET method. I need to test it. When I write in URL request with incorrect iso code of the country, it throws me back a custom exception. So how can I test it?

So here 'UA' is incorrect argument

@Test
fun check_for_incorrect_iso_code() {
    mockMvc.perform(get("/countries/UA"))
        .andDo(print())
        .andExpect(status().is4xxClientError)
}

Test is working, but I need to extend it and check if it throws my custom exception - 'InvalidIsoCodeException' for example.

Thanks for the answer.


Solution

  • Your Java code is throwing an InvalidIsoCodeException but your server/controller cannot throw exceptions. Instead it sends back an HTTP response to the client. The InvalidIsoCodeException is mapped by Spring to a specific response. You're already checking the status of the response with .andExpect(status().is4xxClientError()). You can also verify the body of the response if you want to be more specific.

    If you want to test for the exception then you have to test your controller like a normal Java class without MockMVC.