Controller
@RequestMapping("/getTeacher/{name}")
public String addUser(@PathVariable("name")String name, HttpServletRequest request, HttpServletResponse response, Model model) {
Teacher t = teacherService.getTeacher(1);
System.out.println(t.getGroup().getName() + "-----------" + name);
model.addAttribute("name", name);
model.addAttribute("teacher", t);
model.addAttribute(t);
return "success";
}
@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration(value="")//测试环境使用,用来表示测试环境使用的ApplicationContext将是WebApplicationContext类型的;value指定web应用的根;@ContextHierarchy({//指定容器层次
@ContextConfiguration(name="parent", locations={"classpath:config/spring-hibernate.xml"}),
@ContextConfiguration(name="child", locations={"classpath:config/springAnnotation-servlet.xml"})
})
@Transactional //提供事务支持
@TransactionConfiguration(transactionManager="transactionManager", defaultRollback=true)
public class TestUserController {
@Autowired
private WebApplicationContext wac;
private MockMvc mockMvc;
@Before
public void before() {
mockMvc = MockMvcBuilders.webAppContextSetup(wac).build();
}
/**
* 1、mockMvc.perform执行一个请求;
* 2、MockMvcRequestBuilders.get("/user/1")构造一个请求
* 3、ResultActions.andExpect添加执行完成后的断言
* 4、ResultActions.andDo添加一个结果处理器,表示要对结果做点什么事情,比如此处使用MockMvcResultHandlers.print()输出整个响应结果信息。
* 5、ResultActions.andReturn表示执行完成后返回相应的结果。
* @throws Exception
*/
@Test
public void testGetTeacher() throws Exception {
mockMvc.perform(MockMvcRequestBuilders.get("/getTeacher/zoufeng").param("name", "zoufeng2"))
.andExpect(view().name("success"))
.andExpect(MockMvcResultMatchers.handler().methodName("addUser"))
.andExpect(MockMvcResultMatchers.forwardedUrl("/success.jsp"))
.andExpect(MockMvcResultMatchers.model().attribute("name", "zoufeng"))
.andReturn();
}
}