Testing a Spring Boot application with custom Erro

2019-04-12 07:29发布

问题:

I am trying to test a Spring Boot RestController that should use custom error attributes.

    @Bean
public ErrorAttributes errorAttributes() {
    return new DefaultErrorAttributes() {

        @Override
        public Map<String, Object> getErrorAttributes(
                RequestAttributes requestAttributes,
                boolean includeStackTrace) {
            Map<String, Object> errorAttributes = super.getErrorAttributes(requestAttributes, includeStackTrace);
            Throwable error = getError(requestAttributes);
            return errorAttributes;
        }

    };
}

But when i try to test the custom error attributes using a simple test these properties are not taken into account. The test below actually fires a request and i except that the custom attributes are used. But whatever i seem to do the code seems to be not taken into account.

class TestSpec extends Specification {

    MockMvc mockMvc

    def setup() {
        mockMvc = MockMvcBuilders.standaloneSetup(new HelloWorldController()).build()
    }

    def "Test simple action"() {
        when:
        def response = mockMvc.perform(post("/hello")
                .contentType(MediaType.APPLICATION_JSON)
                .content('{"sayHelloTo": ""}')
        )

        then:
        response.andExpect(status().isOk())
    }
}

Any clue on how i could test if the custom attributes?

回答1:

Spring Boot's error infrastructure works by forwarding requests to an error controller. It's this error controller that uses an ErrorAttributes instance. MockMvc only had fairly basic support for testing the forwarding of requests (you can check that the request would be forwarded, but not the actual outcome of that forward). This means that a MockMvc test that calls your HellowWorldController, either using standalone setup or a web application context-based setup, isn't going to drive the right code path.

A few options:

  • Unit test your custom ErrorAttributes class directly
  • Write a MockMvc-based test that calls Spring Boot's BasicErrorController configured with your custom ErrorAttributes instance
  • Write an integration test that uses RestTemplate to make an actual HTTP call into your service