2013-10-13 45 views
3

我是新來的春天,這是我在堆棧溢出的第一個問題,我的英語水平也基本...MockMvc達到@Controller類雖然servlet映射過濾

我目前繼http://spring.io/guides/tutorials/web/3/和我不明白爲什麼MvcMock可以執行get("/bbb")併到達我的控制器(映射到@RequestMapping("/bbb")),即使AbstractAnnotationConfigDispatcherServletInitializerDispatcherSevlet映射限制爲new String[] { "/aaa" };

這裏是所涉及的代碼...

春季WebAppInitializer

public class WebAppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer { 

@Override 
protected Class<?>[] getRootConfigClasses() { 
    return new Class<?>[] { PersistenceConfig.class, CoreConfig.class }; 
} 

@Override 
protected Class<?>[] getServletConfigClasses() { 
    return new Class<?>[] { WebConfig.class }; 
} 

@Override 
protected String[] getServletMappings() { 
    return new String[] { "/aaa" }; 
} 

@Override 
protected Filter[] getServletFilters() { 

    CharacterEncodingFilter characterEncodingFilter = new CharacterEncodingFilter(); 
    characterEncodingFilter.setEncoding("UTF-8"); 
    return new Filter[] { characterEncodingFilter }; 
} 
} 

春季控制器

@Controller 
@RequestMapping("/bbb") 
public class SiteController { 

private static final Logger LOG = LoggerFactory.getLogger(SiteController.class); 

@Autowired 
private MenuService menuService; 

@RequestMapping(method = RequestMethod.GET) 
@ResponseBody 
public String getCurrentMenu() { 
    ... 
} 

這通過

JUnit測試
@RunWith(SpringJUnit4ClassRunner.class) 
@WebAppConfiguration 
@ContextConfiguration(classes = { PersistenceConfig.class, CoreConfig.class, WebConfig.class }) 
public class WebDomainIntegrationTest { 

private static final String STANDARD = "Yummy Noodles"; 
private static final String CHEF_SPECIAL = "Special Yummy Noodles"; 
private static final String LOW_CAL = "Low cal Yummy Noodles"; 

private MockMvc mockMvc; 

@Autowired 
WebApplicationContext webApplicationContext; 

@Before 
public void setup() { 
    mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build(); 
} 

@Test 
public void thatTextReturned() throws Exception { 
      mockMvc.perform(get("/bbb")).andDo(print()).andExpect(content().string(containsString(STANDARD))) 
      .andExpect(content().string(containsString(CHEF_SPECIAL))).andExpect(content().string(containsString(LOW_CAL))); 

} 

} 

感謝您的幫助!

Laurent

回答

6

歡迎來到Stackoverflow!這是一個很好的第一個問題。

答案是您的MockMvc配置不使用您的WebAppInitializerThis currently isn't supported by the Spring MVC test suite.注意你沒有註冊任何地方。所有你要做的就是設置與

@ContextConfiguration(classes = { PersistenceConfig.class, CoreConfig.class, WebConfig.class }) 

有了這一點,

@WebAppConfiguration 

MockMvc您的上下文結構,將您的上下文(和其他的東西,它看起來對)登記與@ControllerDispatcherServlet。然後它將使用該配置運行測試。該配置中沒有/aaa。所有路徑都是絕對路徑,因爲它們在您的@Controller類中聲明。

+0

謝謝Sotirios! :-) –

+0

所以。我正在嘗試編寫spring security mockmvc測試,並將過濾器鏈配置爲此servlet映射「/ aaa」。我如何配置mockMvc來捕獲servlet配置? –