[Java] [Spring] Exception output test of controller

less than 1 minute read

Basically, the test of controller that receives request is often written using MockMvc. If you want to output an exception, the test of the exception output can be implemented by org.assertj.core.api.Assertions.assertThatThrownBy.

Example

Product code

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class TestController {

    @GetMapping(value = "exception")
    public void throwException() {
        throw new IllegalStateException("Exception");
    }
}

test code


import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;

import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;

@RunWith(SpringRunner.class)
@SpringBootTest
@AutoConfigureMockMvc
public class TestControllerTest {

    @Autowired
    private MockMvc mockMvc;

    @Test
    public void throwExceptionTest() {
        assertThatThrownBy(() ->
                mockMvc.perform(get("/exception"))
        ).hasCause(new IllegalStateException("is an exception"));
    }
}

You can verify the contents of the exception by using .hasCause.

reference

assertThatThrownBy (Reference) How to prevent NestedServletException when testing Spring endpoints? (stack overflow)