您当前的位置: 首页 > 

Mockito测试 示例

梁云亮 发布时间:2020-05-25 18:50:07 ,浏览量:3

相关博客:Mockito原理 本博客相关代码:代码下载

步骤

整个测试过程非常有规律:

  1. 准备测试环境
  2. 通过MockMvc执行请求 3.1. 添加验证断言 3.2. 添加结果处理器 3.3. 得到MvcResult进行自定义断言/进行下一步的异步请求
  3. 卸载测试环境

spring提供了mockMvc模块,可以模拟web请求来对controller层进行单元测试

示例:MockMvc

MockMvc Spring提供了mockMvc模块,可以模拟web请求来对controller层进行单元测试

第一步:添加Maven依赖

    junit
    junit
    4.12


    org.springframework.boot
    spring-boot-starter-web


    org.projectlombok
    lombok
    true


    org.springframework.boot
    spring-boot-starter-test

第二步:统一返回结果相关 Result.java
@Data
@NoArgsConstructor
@AllArgsConstructor
public class Result {
    // 请求响应状态码(200、400、500)
    private int code;
    // 请求结果描述信息
    private String msg;
    // 请求结果数据
    private T data;

    public Result(int code, String msg) {
        this.code = code;
        this.msg = msg;
    }

    public Result(ResultCode resultCode) {
        this.code = resultCode.getCode();
        this.msg = resultCode.getMsg();
    }
}
ResultCode.java
public enum ResultCode {
    // 成功
    OK(200, "OK"),
    // 服务器错误
    INTERNAL_SERVER_ERROR(500, "Internal Server Error");

    // 操作代码
    int code;
    // 提示信息
    String msg;

    ResultCode(int code, String msg) {
        this.code = code;
        this.msg = msg;
    }

    public int getCode() {
        return code;
    }

    public void setCode(int code) {
        this.code = code;
    }

    public String getMsg() {
        return msg;
    }

    public void setMsg(String msg) {
        this.msg = msg;
    }
}
ResultUtil.java
public class ResultUtil {
    /**
     * 操作成功,返回具体的数据、结果码和提示信息
     * 用于数据查询接口
     * @param data
     * @return
     */
    public static Result success(Object data) {
        Result result = new Result(ResultCode.OK);
        result.setData(data);
        return result;
    }
    /**
     * 操作失败,只返回结果码和提示信息
     *
     * @param resultCode
     * @return
     */
    public static Result fail(ResultCode resultCode) {
        return new Result(resultCode);
    }
}
第三步:实体类
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
@Builder
@ToString
public class Dept {
    private Integer deptno;
    private String dname;
    private String loc;
}
第四步:数据库模拟类
public class DeptTable {
    private static ArrayList depts = new ArrayList();
    static {
        depts.add(new Dept(10, "ACCOUNTING", "CHICAGO"));
        depts.add(new Dept(20, "RESEARCH", "DALLAS"));
        depts.add(new Dept(30, "SALES", "CHICAGO"));
        depts.add(new Dept(40, "OPERATIONS", "BOSTON"));
    }
    public static boolean insert(Dept dept) {
        boolean res = depts.add(dept);
        return res;
    }
    public static boolean update(Dept dept) {
        Integer deptno = dept.getDeptno();
        boolean flag = false;
        for (int i = 0; i             
关注
打赏
1688896170
查看更多评论
0.0489s