Rud*_*idt 21 java junit spring spring-mvc mockmvc
我的带@ControllerAdvice注释的控制器看起来像这样:
@ControllerAdvice
public class GlobalControllerExceptionHandler {
@ResponseStatus(value = HttpStatus.UNAUTHORIZED)
@ExceptionHandler(AuthenticationException.class)
public void authenticationExceptionHandler() {
}
}
Run Code Online (Sandbox Code Playgroud)
当然我的开发是测试驱动的,我想在JUnit测试中使用我的异常处理程序.我的测试用例如下所示:
public class ClientQueriesControllerTest {
private MockMvc mockMvc;
@InjectMocks
private ClientQueriesController controller;
@Mock
private AuthenticationService authenticationService;
@Before
public void setup() {
MockitoAnnotations.initMocks(this);
mockMvc = MockMvcBuilders.standaloneSetup(controller).build();
}
@Test
public void findAllAccountRelatedClientsUnauthorized() throws Exception {
when(authenticationService.validateAuthorization(anyString())).thenThrow(AuthenticationException.class);
mockMvc.perform(get("/rest/clients").header("Authorization", UUID.randomUUID().toString()))
.andExpect(status().isUnauthorized());
}
}
Run Code Online (Sandbox Code Playgroud)
可能我需要注册ControllerAdvice课程.怎么做?
Mor*_*erg 30
从Spring 4.2开始,您可以将ControllerAdvice直接注册到StandaloneMockMvcBuilder中:
MockMvcBuilders
.standaloneSetup(myController)
.setControllerAdvice(new MyontrollerAdvice())
.build();
Run Code Online (Sandbox Code Playgroud)
geo*_*and 23
为了激活完整的Spring MVC配置,您需要使用MockMvcBuilders.webAppContextSetup而不是MockMvcBuilders.standaloneSetup.
有关更多详细信息,请查看Spring文档的这一部分.
您的代码如下所示:
@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
@ContextConfiguration("test-config.xml")
public class ClientQueriesControllerTest {
private MockMvc mockMvc;
@Autowired
private WebApplicationContext webApplicationContext;
@Autowired
private AuthenticationService authenticationService;
@Before
public void setup() {
MockitoAnnotations.initMocks(this);
mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build();
}
@Test
public void findAllAccountRelatedClientsUnauthorized() throws Exception {
when(authenticationService.validateAuthorization(anyString())).thenThrow(AuthenticationException.class);
mockMvc.perform(get("/rest/clients").header("Authorization", UUID.randomUUID().toString()))
.andExpect(status().isUnauthorized());
}
}
Run Code Online (Sandbox Code Playgroud)
然后在里面test-config.xml你会添加一个Spring bean,AuthenticationService这是一个模拟.
<bean id="authenticationService" class="org.mockito.Mockito" factory-method="mock">
<constructor-arg value="your.package.structure.AuthenticationService"/>
</bean>
Run Code Online (Sandbox Code Playgroud)
AuthenticationService如果想要重用常规的Spring配置文件而不是创建,您当然可以使用配置文件在测试中注入模拟test-config.xml.
UPDATE
在挖了一下之后,我发现StandaloneMockMvcBuilder(MockMvcBuilders.standaloneSetup)返回的是完全可定制的.这意味着您可以插入您喜欢的任何异常解析器.
但是,由于您使用@ControllerAdvice,以下代码将无法正常工作.但是,如果您的@ExceptionHandler方法在同一个控制器中,则您需要更改的代码如下:
mockMvc = MockMvcBuilders.standaloneSetup(controller).setHandlerExceptionResolvers(new ExceptionHandlerExceptionResolver()).build();
Run Code Online (Sandbox Code Playgroud)
更新2
更多挖掘给出了如何在使用时注册正确的异常处理程序的答案@ControllerAdvice.
您需要将测试中的设置代码更新为以下内容:
@Before
public void setUp() throws Exception {
final ExceptionHandlerExceptionResolver exceptionHandlerExceptionResolver = new ExceptionHandlerExceptionResolver();
//here we need to setup a dummy application context that only registers the GlobalControllerExceptionHandler
final StaticApplicationContext applicationContext = new StaticApplicationContext();
applicationContext.registerBeanDefinition("advice", new RootBeanDefinition(GlobalControllerExceptionHandler.class, null, null));
//set the application context of the resolver to the dummy application context we just created
exceptionHandlerExceptionResolver.setApplicationContext(applicationContext);
//needed in order to force the exception resolver to update it's internal caches
exceptionHandlerExceptionResolver.afterPropertiesSet();
mockMvc = MockMvcBuilders.standaloneSetup(controller).setHandlerExceptionResolvers(exceptionHandlerExceptionResolver).build();
}
Run Code Online (Sandbox Code Playgroud)
小智 20
通过以下解决方案超过NestedServletException ...
final StaticApplicationContext applicationContext = new StaticApplicationContext();
applicationContext.registerSingleton("exceptionHandler", GlobalControllerExceptionHandler.class);
final WebMvcConfigurationSupport webMvcConfigurationSupport = new WebMvcConfigurationSupport();
webMvcConfigurationSupport.setApplicationContext(applicationContext);
mockMvc = MockMvcBuilders.standaloneSetup(controller).
setHandlerExceptionResolvers(webMvcConfigurationSupport.handlerExceptionResolver()).
build();
Run Code Online (Sandbox Code Playgroud)