SpringBoot16 MockMvc的使用、JsonPath的使用、请求参数问题、JsonView、分页查询参数、JsonProperty...

本文详细介绍了如何在SpringBoot中使用MockMvc进行MVC测试,包括JsonPath的使用、各种请求参数如PathVarible、RequestParam和RequestBody的处理,以及JsonView在不同场景下的应用。此外,还讲解了分页查询参数的处理,如使用Pageable接收前端参数,以及JsonProperty解决前后端变量名不一致的问题。
摘要由CSDN通过智能技术生成

 

1 MockMvc的使用

  利用MockMvc可以快速实现MVC测试

  坑01:利用MockMvc进行测试时应用上下文路径是不包含在请求路径中的

  1.1 创建一个SpringBoot项目

    项目脚手架

  1.2 创建一个用户实体类

package cn.test.demo.base_demo.entity.po;

import java.util.Date;

/**
 * @author 王杨帅
 * @create 2018-05-05 22:03
 * @desc 用户实体类
 **/
public class User {
    private Integer userId;
    private String userName;
    private String password;
    private Date birthday;

    public Integer getUserId() {
        return userId;
    }

    public void setUserId(Integer userId) {
        this.userId = userId;
    }

    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public Date getBirthday() {
        return birthday;
    }

    public void setBirthday(Date birthday) {
        this.birthday = birthday;
    }
}
User.java

  1.3 创建一个用户控制类

package cn.test.demo.base_demo.controller;

import cn.test.demo.base_demo.entity.po.User;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;

/**
 * @author 王杨帅
 * @create 2018-05-05 22:02
 * @desc 用户模块控制层
 **/
@RestController
@RequestMapping(value = "/user")
public class UserController {

    @GetMapping
    public List<User> queryList() {
        List<User> userList = new ArrayList<>();
        userList.add(new User());
        userList.add(new User());
        userList.add(new User());
        return userList;
    }

}
UserController.java

  1.4 创建一个测试类

    该测试类主要测试用户控制类中的相关方法

    1.4.1 引入测试类注解以及日志注解
@RunWith(SpringRunner.class)
@SpringBootTest
@Slf4j
    1.4.2 依赖注入WebApplicationContext
    @Autowired
    private WebApplicationContext wac;
    1.4.3 实例化MockMvc
    private MockMvc mockMvc;

    @Before
    public void setup() {
        mockMvc = MockMvcBuilders.webAppContextSetup(wac).build();
    }
    1.4.4 利用MockMvc对象模拟HTTP请求
    @Test
    public void queryList() throws Exception {
        String result = mockMvc.perform(
                    MockMvcRequestBuilders.get("/user")
                    .contentType(MediaType.APPLICATION_JSON_UTF8)
                )
                .andExpect(MockMvcResultMatchers.status().isOk())
                .andReturn().getResponse().getContentAsString();
        log.info("===/" + className + "/queryList===" + result);
    }
    1.4.5 测试类代码汇总
package cn.test.demo.base_demo.controller;

import lombok.extern.slf4j.Slf4j;
import org.junit.Before;
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.http.MediaType;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.MockMvcBuilder;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.result.MockMvcResultMatchers;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;

import static org.junit.Assert.*;

@RunWith(SpringRunner.class)
@SpringBootTest
@Slf4j
public class UserControllerTest {

    private final String className = getClass().getName();

    @Autowired
    private WebApplicationContext wac;

    private MockMvc mockMvc;

    @Before
    public void setup() {
        mockMvc = MockMvcBuilders.webAppContextSetup(wac).build();
    }

    @Test
    public void queryList() throws Exception {
        String result = mockMvc.perform(
                    MockMvcRequestBuilders.get("/user")
                    .contentType(MediaType.APPLICATION_JSON_UTF8)
                )
                .andExpect(MockMvcResultMatchers.status().isOk())
                .andReturn().getResponse().getContentAsString();
        log.info("===/" + className + "/queryList===" + result);
    }

}
View Code

 

2 JsonPath

  JsonPath是GitHub上的一个开源项目,主要用来对Json格式的数据进行一些处理

  技巧:jsonPath是MockMvcResultMatchers中的一个静态方法

  具体使用:点击前往

  2.1 简单实例

    @Test
    public void test01() throws Exception {
        mockMvc.perform(
                        MockMvcRequestBuilders.get("/user")
                            .contentType(MediaType.APPLICATION_JSON_UTF8)
                )
                .andExpect(MockMvcResultMatchers.status().isOk())
                .andExpect(MockMvcResultMatchers.jsonPath("$.length()").value(3));
    }

 

3 请求参数

  3.1 PathVarible

    主要获取请求路径中的数据

    技巧01:PathVarible获取到的数据是请求路径的一部分

    技巧02:@PathVariable注解中的name和value两个成员的作用是一样的,是用来解决路径名和请求处理方法形参名不一致的问题

    技巧03:@PathVariable支持正则表达式,如果路径参数不满足正则表达式就会匹配失败;参考博文

//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by Fernflower decompiler)
//

package org.springframework.web.bind.annotation;

import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import org.springframework.core.annotation.AliasFor;

@Target({ElementType.PARAMETER})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface PathVariable {
    @AliasFor("name")
    String value() default "";

    @AliasFor("value")
    String name() default "";

    boolean required() default true;
}
PathVariable.java

    

    3.1.1 控制类
package cn.test.demo.base_demo.controller;

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值