springboot中的springmvc流程测试
当然,以下代码得先引入springboot需要的各种架包,其中包含spring-boot-starter-test
```java
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.MvcResult;
import org.springframework.test.web.servlet.RequestBuilder;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import com.fasterxml.jackson.databind.ObjectMapper;
import cn.xdl.RunUserBoot;
import cn.xdl.ydma.common.YdmaConstant;
import cn.xdl.ydma.common.YdmaResult;
import cn.xdl.ydma.controller.UserController;
@RunWith(SpringRunner.class)//指定一个junit启动器,可以在启动时创建Spring容器对象
@SpringBootTest(classes=RunUserBoot.class)//classes指定的是启动类
public class TestUserRegister {
@Autowired
private UserController controller;
// @Test//测试的是一个方法
// public void test2() {
// YdmaResult ydmaResult = controller.regist("x12", "123456");
// Assert.assertEquals(YdmaConstant.ERROR, ydmaResult.getCode());
// Assert.assertEquals(YdmaConstant.REGIST_NAME_ERROR_MSG, ydmaResult.getMsg());
// }
@Test//测试SpringMVC处理流程
public void test1() throws Exception {
//创建MockMvc对象,可以发送HTTP请求,接收响应结果
MockMvc mock = MockMvcBuilders.standaloneSetup(controller).build();
//使用mock对象发送POST请求,如果需要测试get请求,使用 MockMvcRequestBuilders.get
RequestBuilder request =
MockMvcRequestBuilders.post("/user/regist")
.param("name", "xdl")
.param("password", "123456");
MvcResult result = mock.perform(request).andReturn();
//获取返回的结果
String jsonStr = result.getResponse().getContentAsString();
//System.out.println(jsonStr);
//将返回jsonStr结果转成YdmaResult对象,然后使用断言比对结果和预期
ObjectMapper mapper = new ObjectMapper();
YdmaResult ydmaResult = mapper.readValue(jsonStr, YdmaResult.class);
Assert.assertEquals(YdmaConstant.ERROR, ydmaResult.getCode());
Assert.assertEquals(YdmaConstant.REGIST_NAME_ERROR_MSG, ydmaResult.getMsg());
}
@Test//测试SpringMVC处理流程
public void test2() throws Exception {
//创建MockMvc对象,可以发送HTTP请求,接收响应结果
MockMvc mock = MockMvcBuilders.standaloneSetup(controller).build();
//使用mock对象发送GET请求
RequestBuilder request =
MockMvcRequestBuilders.get("/user/get")
.param("id", "11");
MvcResult result = mock.perform(request).andReturn();
//获取返回的结果
String jsonStr = result.getResponse().getContentAsString();
System.out.println(jsonStr);
}
}