爲了激活完整的Spring MVC配置,您需要使用MockMvcBuilders.webAppContextSetup
而不是MockMvcBuilders.standaloneSetup
。
檢查出this 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
這是一個模擬。
你當然可以使用配置文件注入在測試中模擬AuthenticationService
如果要重用,而不是創建test-config.xml
你經常Spring配置文件。
UPDATE
了一下週圍挖後,我發現,通過(MockMvcBuilders.standaloneSetup
)返回StandaloneMockMvcBuilder
是完全可定製的。這意味着你可以插入你喜歡的任何異常解析器。
但是由於您使用的是@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();
}
您是否試過'MockMvcBuilders.webAppContextSetup'選項,如http://docs.spring.io/spring-framework/docs/current/spring-framework-reference/html/testing.html#spring-mvc-test-框架而不是'MockMvcBuilders.standaloneSetup'? – geoand 2014-09-01 10:57:54