我是 Spring 新手,这是我在 Stack Overflow 中的第一个问题,我的英语也很基础......
我目前正在关注http://spring.io/guides/tutorials/web/3/,我不明白为什么 MvcMock 可以执行get("/bbb")
并到达我的控制器(映射到@RequestMapping("/bbb")
),甚至将映射AbstractAnnotationConfigDispatcherServletInitializer
限制为?DispatcherSevlet
new String[] { "/aaa" };
这是涉及的代码...
Spring 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)));
}
}
非常感谢你的帮助!
洛朗