应用场景:表现层代码在测试时,需要部署服务器,启动服务器测试,对于频繁的测试,由于服务器启动缓慢,测试起来很不方便。
spring-test提供了虚拟mvc请求,可以模拟请求进行测试
需要jar包:spring-test.jar
@ContextConfiguration(locations = {"classpath:applicationContext.xml","classpath:springmvc.xml"})
@WebAppConfiguration//此注解为WebApplicationContext从springmvc IOC中取出赋值
@RunWith(SpringJUnit4ClassRunner.class)
public class UserMVCTest {
@Autowired
private WebApplicationContext context;
//虚拟mvc请求
private MockMvc mockMvc;
//初始化mockMvc
@Before
public void initMockMvc(){
mockMvc = MockMvcBuilders.webAppContextSetup(context).build();
}
@Test
public void testVerifyUserName() throws Exception {
//发送请求,并获取返回值(会执行action方法中的代码,包括输出语句)
mockMvc.perform(MockMvcRequestBuilders.get("/user/verifyUserName")
.param("userName", "wang5"));
}
@Test
public void testLogin() throws Exception{
MvcResult result = mockMvc.perform(MockMvcRequestBuilders.get("/user/login")
.param("userName", "zhang3").param("password", "1234")).andReturn();
User user = (User) result.getRequest().getSession().getAttribute("user");
System.out.println(user);
}
@Test
public void testRegister() throws Exception{
mockMvc.perform(MockMvcRequestBuilders.get("/user/register")
.param("userName", "wang5").param("password", "1234"));
}
}
来源:CSDN
作者:别碰我辣条
链接:https://blog.csdn.net/weixin_44134144/article/details/104626314