为了激活完整的 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());
}
}
然后在里面test-config.xml
你会添加一个 Spring bean,因为AuthenticationService
它是一个 mock。
<bean id="authenticationService" class="org.mockito.Mockito" factory-method="mock">
<constructor-arg value="your.package.structure.AuthenticationService"/>
</bean>
如果要重用AuthenticationService
常规 Spring 配置文件而不是创建test-config.xml
.
更新
经过一番挖掘,我发现StandaloneMockMvcBuilder
( MockMvcBuilders.standaloneSetup
) 返回的内容是完全可定制的。这意味着您可以插入您喜欢的任何异常解析器。
但是,由于您使用的是@ControllerAdvice
,因此下面的代码将不起作用。但是,如果您的@ExceptionHandler
方法在同一个控制器中,则您必须更改的代码如下:
mockMvc = MockMvcBuilders.standaloneSetup(controller).setHandlerExceptionResolvers(new ExceptionHandlerExceptionResolver()).build();
更新 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();
}