Spring Boot Junit单元测试MockMvc使用(MockHttpServletRequestBuilder MvcResult ModelAndView json)

项目中使用了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数据解决办法

 

  • 14
    点赞
  • 68
    收藏
    觉得还不错? 一键收藏
  • 7
    评论
生成一个使用JUnit进行单元测试Spring boot 工程,可以按照以下步骤进行: 1. 使用Spring Initializr在线工具或者在Eclipse、IntelliJ IDEA等IDE中创建一个Spring boot项目,选择Web、JPA和MySQL等依赖。 2. 在pom.xml文件中添加JUnitMockito等测试依赖。 ```xml <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <scope>test</scope> </dependency> <dependency> <groupId>org.mockito</groupId> <artifactId>mockito-core</artifactId> <scope>test</scope> </dependency> ``` 3. 创建一个测试类,使用JUnitMockito等工具进行测试。 ```java @RunWith(SpringRunner.class) @SpringBootTest public class UserServiceTest { @MockBean private UserRepository userRepository; @Autowired private UserService userService; @Test public void testGetUserById() { User user = new User(); user.setId(1L); user.setName("Test"); user.setAge(18); Mockito.when(userRepository.findById(1L)).thenReturn(Optional.of(user)); User result = userService.getUserById(1L); Assert.assertEquals(result.getName(), "Test"); Assert.assertEquals(result.getAge(), 18); } } ``` 在这个例子中,使用@RunWith和@SpringBootTest注解来配置测试环境,使用@MockBean注解来模拟依赖的UserRepository对象,使用@Autowired注解来注入需要测试的UserService对象,使用Mockito.when和Assert.assertEquals等方法来进行测试。 4. 运行测试用例,查看测试结果。 在Eclipse、IntelliJ IDEA等IDE中,可以右键点击测试类并选择Run As JUnit Test来运行测试用例。测试结果将会在控制台中输出。
评论 7
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值