Java SpringBoot单元测试

在后端开发接口时,有时间一定要进行接口的单元测试,保证自己的代码质量,避免功能提测后因为低级错误被测试打回。

pom.xml 文件里面添加两个测试扩展包:

1
2
3
4
5
6
7
8
9
10
11
12
...
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-test</artifactId>
    <scope>test</scope>
</dependency>
<dependency>
    <groupId>org.junit.jupiter</groupId>
    <artifactId>junit-jupiter-api</artifactId>
    <scope>test</scope>
</dependency>
...  

创建一个User的实体类:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
package com.demo.www.model.entity;
 
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.experimental.Accessors;
 
import java.io.Serializable;
 
/**
 * 用户表
 * @author AnYuan
 */
@Data
@EqualsAndHashCode(callSuper = false)
@Accessors(chain = true)
@TableName("users")
public class User implements Serializable {
 
    @TableId(value = "id", type = IdType.AUTO)
    private Integer id;
 
    /**
     * 用户名
     */
    private String name;
 
    /**
     * 手机号
     */
    private String phone;
}

创建一个UserService:

1
2
3
4
5
6
7
8
9
10
11
12
package com.demo.www.service;
 
import com.baomidou.mybatisplus.extension.service.IService;
import com.demo.www.model.entity.User;
 
/**
 * 用户表 服务类
 * @author AnYuan
 */
public interface UserService extends IService<User> {
     
}

创建一个Controller作为接口测试:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
package com.demo.www.controller;
 
import com.demo.www.model.entity.User;
import com.demo.www.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
 
/**
 * 用户Controller
 * @author AnYuan
 */
 
@Slf4j
@RestController
public class UserController {
 
    @Autowired
    private UserService userService;
 
    @GetMapping("/user/{id}")
    public User getUser(@PathVariable String id) {
        return userService.getById(id);
    }
}

接口写好之后,创建一个测试类。在IDEA里面鼠标选中方法右键 Generate 可直接生成测试类

这里配置 @AutoConfigureMockMvc 注解自动注入 MockMvc 类进行测试

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
package com.demo.www.controller;
 
import org.hamcrest.core.StringContains;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
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.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.result.MockMvcResultHandlers;
import org.springframework.test.web.servlet.result.MockMvcResultMatchers;
 
@RunWith(SpringRunner.class)
@SpringBootTest
@AutoConfigureMockMvc
public class UserControllerTest {
 
    @Autowired
    private MockMvc mockMvc;
 
    /**
     *
     * perform : 执行MockMvcRequestBuilders的请求并返回一个类型,该类型结果可以链式操作。
     * MockMvcRequestBuilders请求的类型包括:get(),post(),put(),delete()。
     *
     * accept : 希望接收的数据类型
     * header : 表明请求客户端类型
     * param : 请求参数
     * ...
     *
     * andExpect : 添加 MockMvcResultMatchers 的结果验证器。可以判断http状态码和返回json是否为包含期望值
     * andDo: 添加 MockMvcResultHandlers 的结果处理器,可以打印返回的内容
     */
 
    @Test
    public void getUser() throws Exception {
        mockMvc.perform(MockMvcRequestBuilders.get("/user/1")
                .accept(MediaType.APPLICATION_JSON)
                .header("X-Client", "app")
                .andExpect(MockMvcResultMatchers.status().isOk())
                .andExpect(MockMvcResultMatchers.content().string(StringContains.containsString("age")))
                .andDo(MockMvcResultHandlers.print())
                .andReturn();
    }

  最后执行该测试方法,正常情况下控制台输出:

  

   Url不存在异常:

  

  返回的数据里面没有包含期望的字符串异常:

 

 MockMvc更多功能使用可以去MockMvc的官网查阅

 

  MockMvc官方文档:https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/test/web/servlet/MockMvc.html

  Spring官方测试用例:https://spring.io/guides/gs/testing-web/

 

posted @   安逺  阅读(1182)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
点击右上角即可分享
微信分享提示