MockMvc单元测试

背景

1、使用 Squaretest 生成controller的测试类(略)
生成的代码大概如下:
该文章只简单记录使用的一个过程,和遇到过的一个小问题,
就是,requestbody 传参无效


import com.alibaba.fastjson.JSON;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.mock.web.MockHttpServletResponse;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.reflections.Reflections.log;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;

@RunWith(SpringRunner.class)
@WebMvcTest(TaskController.class)
public class TaskControllerTest {

    @Autowired
    private MockMvc mockMvc;

    @Test
    public void testDataHis() throws Exception {
        // Setup
        HisFo hisFo = new HisFo();
        hisFo.setId("222222");
        hisFo.setCode("linye");

        log.info("fo: {}", JSON.toJSONString(hisFo));

        // Run the test
        final MockHttpServletResponse response = mockMvc.perform(
                post("/v1/task/biz-data/history")
                        .content(JSON.toJSONString(hisFo)).contentType(MediaType.APPLICATION_JSON_UTF8)
                        .accept(MediaType.APPLICATION_JSON_UTF8))
                .andReturn().getResponse();

        // Verify the results
        assertEquals(HttpStatus.OK.value(), response.getStatus());
        String contentAsString = response.getContentAsString();
        log.info("bizData his: {}", contentAsString);
        assertNotNull(JSON.parseObject(contentAsString).getJSONObject("data"));
    }
}

问题描述:
1、这个接口的参数 hisFo, 它的两个属性都是必填的,一开始,只写了 id 的值,就报错:


FlashMap:
       Attributes = null

MockHttpServletResponse:
           Status = 400
    Error message = null
          Headers = {}
     Content type = null
             Body = 
    Forwarded URL = null
   Redirected URL = null
          Cookies = []

java.lang.AssertionError: 
Expected :200
Actual   :400
<Click to see difference>

只告诉我,400了,但也没有更多的有效报错。
一开始,还以为参数没有传好,没有接收到。。。在捣鼓 “mockMvc 如何传参” 找了很久,但发现写法就是没有问题。
后来才知道, 原来参数没有传好,这里是看不到原因的。。。当然controller 那里也没有进入,所以一开始有一点点疑惑。

再做一点点笔记:
mockMvc 如何传参

mockMvc.perform(
                post("/v1/task/biz-data/history")
                        .content(JSON.toJSONString(hisFo))
                        .contentType(MediaType.APPLICATION_JSON_UTF8)
                        .accept(MediaType.APPLICATION_JSON_UTF8))

.content(JSON.toJSONString(hisFo))   // 这个就是传参。。。把对象转 jsonstring 就行。。。

posted @ 2022-12-06 17:26  aaacarrot  阅读(194)  评论(0编辑  收藏  举报