问题描述
在我的项目中,我使用具有以下依赖项的 Rest Assured MockMVC:
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>
我的测试类看起来像:
TestController testController = new TestController();
@Before
public void configureRestAssuredForController() {
RestAssuredMockMvc.standaloneSetup(testController);
}
我在控制器类中定义了几个 ExceptionHandler.在我的 JUnit 测试中,我可以验证在控制器类中定义的请求路径和处理程序.
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.
但是 - 当我使用 @ControllerAdvice
将处理程序移动到一个单独的类时,处理程序不会从测试中调用.
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.
但我不知道如何在独立模式下将异常处理程序添加到 RestAssuredMockMvc 以使其工作.
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.
推荐答案
基于这个答案,我创建了一个对我有用的解决方案:
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)
);
}
所以我的 GlobalExceptionHandler 是使用 StaticApplicationContext 初始化的,然后我从中检索 handlerExceptionResolver 并将其传递给 RestAssuredMockMvc standaloneSetup
So my GlobalExceptionHandler is initialized using StaticApplicationContext and then I retrieve handlerExceptionResolver from it and pass it into RestAssuredMockMvc standaloneSetup
这篇关于放心 + 模拟 MVC @ControllerAdvice的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!