Rest Assured + Mock MVC @ControllerAdvice

主宰稳场 提交于 2019-12-03 20:51:25
ilyailya

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

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); }

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!