[JAVA] [Spring] Controller exception output test

Tests for controllers that accept requests are often written using MockMvc. If you want to output an exception, you can implement a test of the exception output with ʻ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("Exception"));
    }
}

You can use .hasCause to verify the contents of the exception.

reference

[assertThatThrownBy (Reference)](https://joel-costigliola.github.io/assertj/core-8/api/org/assertj/core/api/Assertions.html#assertThatThrownBy-org.assertj.core.api.ThrowableAssert .ThrowingCallable-) How to prevent NestedServletException when testing Spring endpoints?(stack overflow)

Recommended Posts

[Spring] Controller exception output test
Test Spring framework controller with Junit
Test controller with Mock MVC in Spring Boot
Spring Boot exception handling
[Test code learning / output]
Spring Model View Controller Flow
[JUnit] Test the thrown exception
Spring single item validation test
Spring Security usage memo test
Spring boot controller method memo
Sample code to unit test a Spring Boot controller with MockMvc
How to unit test Spring AOP
Write test code in Spring Boot
Output test coverage with clover + gradle
Use DBUnit for Spring Boot test
Output JUnit test report in Maven
Spring Data JPA SQL log output