springMVC test

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();
}

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值