项目中使用了MockMvcRequestBuilders这个类来实现单元测试

特此举例get和post请求带Cookie,带参数,带对象,表单提交,url路径提交,

针对@ModelAttribute,@RequestBody传参传对象

获取返回对象MockHttpServletRequestBuilder  MvcResult  ModelAndView,返回视图/json/字符串解析

故作笔记,也方便日后查阅复习.

单元测试框必要的注入都要有,一个小的框架就出来了

@RunWith(SpringRunner.class)
@SpringBootTest
public class domeTest {
    @Autowired
    private WebApplicationContext context;

    protected MockMvc mvc;

    @Before
    public void setUp() {
        mvc = MockMvcBuilders.webAppContextSetup(context).build();
    }

    @Test
    public void doem() {
    }

}

1.各种请求入参

//发送请求举例

        //post请求
        MockHttpServletRequestBuilder post = MockMvcRequestBuilders.post("/test");
        //get请求
        MockHttpServletRequestBuilder get = MockMvcRequestBuilders.get("/test");

        //post请求    带Cookie
        MockHttpServletRequestBuilder post_cookie = MockMvcRequestBuilders.post("/test")
                .cookie(new Cookie("cookieName","value"));//自己填键值对
        //get请求     带Cookie
        MockHttpServletRequestBuilder get_cookie = MockMvcRequestBuilders.post("/test")
                .cookie(new Cookie("cookieName","value"));//自己填键值对

        //post请求    带session
        MockHttpServletRequestBuilder post_cookie_session = MockMvcRequestBuilders.post("/test")
                .sessionAttr("sessionName","value");
        //get请求    带session
        MockHttpServletRequestBuilder get_cookie_session = MockMvcRequestBuilders.get("/test")
                .sessionAttr("sessionName","value");


        //post请求    带Cookie     带参
        //另外也可适用场景 使用@ModelAttribute("formName")注解接收form表单对象
        //例子:
        //    @PostMapping("/submitOrder")
        //    public ModelAndView submitOrder (@ModelAttribute("orderForm") ServiceProductOrder serviceProductOrder)
        MockHttpServletRequestBuilder post_cookie_par = MockMvcRequestBuilders.post("/test")
                .cookie(new Cookie("cookieName","value"))//自己填键值对
                .param("userName","admin")//有@RequestParam注解优先对应,否则对应着表单的input标签的name属性的  值及value
                .param("pass","admin");//用@ModelAttribute注解的直接对应表单内容

        //get请求     带Cookie     带参方法一(用方法填充)
        MockHttpServletRequestBuilder get_cookie_par_one = MockMvcRequestBuilders.post("/test")
                .cookie(new Cookie("cookieName","value"))//自己填键值对
                //有@RequestParam注解优先对应,否则对应着表单的input标签的name属性的  值及value
                .param("userName","admin")
                .param("pass","admin");
        //get请求     带Cookie     带参方法二(url路径拼接)
        MockHttpServletRequestBuilder get_cookie_par_two = MockMvcRequestBuilders.post("/test?userName=admin&pass=admin")
                .param("pass","admin");


        //post请求    带Cookie
        //适用场景:使用@RequestBody注解接收对象
        //例子:@PostMapping("/submitOrder")
        //     public ModelAndView submitOrder (@RequestBody ServiceProductOrder serviceProductOrder) {
        Admin  admin=new Admin();
        admin.setLoginName("admin");
        admin.setLoginPassword("admin");//填一些必要的参数等.
        MockHttpServletRequestBuilder post_cookie_obj = MockMvcRequestBuilders.post("/test")
                .cookie(new Cookie("cookieName","value"))//自己填键值对
                .contentType(MediaType.APPLICATION_JSON).content(JSONObject.toJSONString(admin));//阿里巴巴的json序列化

        //MultipartFile文件上传请求
        String filename = "images/sy_02.png";//测试文件
        InputStream inStream = getClass().getClassLoader().getResourceAsStream(filename);
        MockMultipartFile mfile = new MockMultipartFile("file", "sy_02.png", "png", inStream);
        MockMultipartHttpServletRequestBuilder file = MockMvcRequestBuilders.multipart("/file/upload").file(mfile);

 2.各种请求Response处理

上面的代码中都返回了MockHttpServletRequestBuilder(以及文件的MockMultipartHttpServletRequestBuilder)对象,接下来就是执行判断返回内容,这些返回值都继承于RequestBuilder

 

//执行请求 返回相应的MvcResult    (mvc这个参数,看最上面的框架怎么注入的)
       //request 就是MockHttpServletRequestBuilder类
        MvcResult mvcResult = mvc.perform(request).andReturn();

        //获取状态码
        int status = mvcResult.getResponse().getStatus();//500状态码  302状态码  404状态码 200状态码等
        //获取返回 @ResponseBody json字符串 : 进行反序列化处理即可
        //注意: 500/400/302则是返回的HTML源码String类型
        String contentAsString = mvcResult.getResponse().getContentAsString();

        //返回ModelAndView  获取里面的页面路径
        //代码: model.setViewName("/index");
        ModelAndView mv = mvcResult.getModelAndView();
        String  url=mv.getViewName(); //得到/index

        //返回ModelAndView  判断里面state参数
        // model.addObject("state", 1);
        ModelAndView mv = mvcResult.getModelAndView();
        Map<String, Object> model = mv.getModel();
        Integer state = (Integer) model.get("state");

        //返回ModelAndView  判断里面的集合/map/对象
        // PageInfo<Admin> list=new PageInfo<>();
        // model.addObject("AdminList", list);
        ModelAndView mv1 = mvcResult.getModelAndView();
        Map<String, Object> model1 = mv1.getModel();
        ((PageInfo<Admin>) model1.get("AdminList")).getList().size();//得到list长度

ps:返回的json字符串我个人喜欢使用转化为JSONObject再加上Assert断言使用,也挺方便的

JSONObject jsonObject = JSONObject.parseObject(jsonString);
Assert.assertEquals(0,jsonObject.getIntValue("code"));

写代码时翻的资料:

Junit测试Controller(MockMVC使用),传输@RequestBody数据解决办法