Rest Assured + Mock MVC @ControllerAdvice

2020-06-27 07:46发布

问题:

In my project I am using Rest Assured MockMVC with the following dependency:

<dependency>
    <groupId>com.jayway.restassured</groupId>
    <artifactId>spring-mock-mvc</artifactId>
    <version>2.9.0</version>
</dependency>

And my test class looks like:

TestController testController = new TestController();
@Before
public void configureRestAssuredForController() {
    RestAssuredMockMvc.standaloneSetup(testController);
}

I have a couple of ExceptionHandlers defined in the controller class. In my JUnit tests I could verify the request paths and the handlers when defined in the controller class.

However - When I moved the handlers to a separate class with @ControllerAdvice, handlers are not being invoked from the tests.

I understood that it is because of the standalone set up for the controller,which probably could not load handlers defined in another class.

But I couldn't figure out how do I add the exception handlers to the RestAssuredMockMvc,in standalone mode to make this work.

I am struggling and any help is much appreciated please.

回答1:

Based on this answer I've created a solution that works great for me:

/**
 * Initializes GlobalExceptionHandler advice using the StaticApplicationContext with the single bean.
 *
 * @return HandlerExceptionResolver instantiated based on the GlobalExceptionHandler
 */
private HandlerExceptionResolver initGlobalExceptionHandlerResolvers() {
    StaticApplicationContext applicationContext = new StaticApplicationContext();
    applicationContext.registerSingleton("exceptionHandler", GlobalExceptionHandler.class);

    WebMvcConfigurationSupport webMvcConfigurationSupport = new WebMvcConfigurationSupport();
    webMvcConfigurationSupport.setApplicationContext(applicationContext);

    return webMvcConfigurationSupport.handlerExceptionResolver();
}

@Before
public void setup() {
    HandlerExceptionResolver handlerExceptionResolver = initGlobalExceptionHandlerResolvers();

    RestAssuredMockMvc.standaloneSetup(
            MockMvcBuilders
                    .standaloneSetup(controller)
                    .setHandlerExceptionResolvers(handlerExceptionResolver)
    );
}

So my GlobalExceptionHandler is initialized using StaticApplicationContext and then I retrieve handlerExceptionResolver from it and pass it into RestAssuredMockMvc standaloneSetup



回答2:

I upgraded Spring to 4.3.1.RELEASE and did the following to make it work -

GlobalControllerExceptionHandler globalControllerExceptionHandler = new GlobalControllerExceptionHandler();
    @Before 
    public void given_rest_assured_is_configured_with_cloud_study_controller()
        throws Exception {
        mockMvc = MockMvcBuilders.standaloneSetup(cloudStudyCountryController)
            .setControllerAdvice(globalControllerExceptionHandler).build();
        RestAssuredMockMvc.mockMvc(mockMvc);
        dataObj.setCloudDataObjectCreateProcessor(createprocessor);
    }