Spirng Boot 使用Junit4单元测试进行RESTful接口测试

上次开会前端说到:我们后端的接口发生了变化没有通知到他们,导致他们写好的功能不能使用。关于这个问题我想可以通过单元测试来解决。在这里我先抛个砖头,大家有什么好的想法记得不吝于赐教。下面用一个简单的Dome来说明。

构建项目

pom里面一些关键的依赖包

<!--用于数据库管理-->
<dependency>
    <groupId>org.flywaydb</groupId>
    <artifactId>flyway-core</artifactId>
</dependency>
<!--测试依赖包-->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-test</artifactId>
    <scope>test</scope>
</dependency>
<!--内存数据库用于测试-->
<dependency>
    <groupId>com.h2database</groupId>
    <artifactId>h2</artifactId>
    <scope>test</scope>
</dependency>
  • spirng boot提供了测试框架我们只要引入spring-boot-starter-test 就可以了。
  • spirng boot还集成了flyway flyway简单入门,我们可以用这个工具来帮我们初始化测试用的数据表。 当然不用flywayhibernate也有反向生成数据表的功能
  • H2是一个免安装内嵌在运行程序里的一个数据库,这里我用它来作为我们的单元测试使用的数据库。这个数据库运行在内存中生命周期与单元测试生命周期一样。也就是说每次运行都是新的库。单元测试的数据是不会写到mysql库里的。

建立测试目标

创建一个普通的RESTful类UserController作为测试目标

/**
 * @author zengxc
 * @since 2018/3/23
 */
@RestController
public class UserController {
    @Autowired
    private UserJpa userJpa;

    /**
     * 查找所有用户
     * @return 用户列表
     */
    @GetMapping("/user")
    public List<User> list(){
        return userJpa.findAll();
    }

    /**
     * 根据用户ID查找用户信息
     * @param id 用户ID
     * @return 用户信息
     */
    @GetMapping("/user/{id}")
    public User get(@PathVariable("id") long id){
        return userJpa.findOne(id);
    }

    /**
     * 创建一个用户
     * @param user 用户信息
     * @return 用户信息
     */
    @PostMapping("/user")
    public User create(@RequestBody User user){
        return userJpa.save(user);
    }

    /**
     * 更新用户
     * @param user 用户信息
     * @return
     */
    @PutMapping("/user")
    public User update(@RequestBody User user){
        return userJpa.save(user);
    }
}

这个类提供了对用户进行增、查、改功能的RESTful接口

建立测试类

IDEA提供了快速创建测试类的方法:把光标放到在类名处,然后按alt+enter>create test就可以创建一个测试类UserControllerTest

/**
 * @author zengxc
 * @since 2018/3/23
 */
@RunWith(SpringRunner.class)
@SpringBootTest
@AutoConfigureMockMvc
public class UserControllerTest {

    @Autowired
    private MockMvc mvc;

    @Test
    public void test() throws Exception {
        RequestBuilder request;

        // 1、get查一下user列表应该为空
        request = get("/user");
        mvc.perform(request)
                .andExpect(status().isOk())
                .andExpect(content().string(equalTo("[]")));
        // 2、post提交一个user
        request = post("/user/")
                .contentType(MediaType.APPLICATION_JSON)
                .accept(MediaType.APPLICATION_JSON)
                .content("{\"name\":\"zxc\",\"age\":18}");
        mvc.perform(request)
                .andDo(print())
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.name",is("zxc")));
        // 3、get查一下user列表,应该不为空
        request = get("/user");
        mvc.perform(request)
                .andExpect(status().isOk())
                .andExpect(content().string(not("")))
                .andExpect(content().string(not("[]")));
        // 4、get查一下user id 等于1的用户,应该不为空,age等于18
        request = get("/user/{id}",1);
        mvc.perform(request)
                .andExpect(status().isOk())
                .andExpect(content().string(not("")))
                .andExpect(jsonPath("$.age").value(18));

        // 4、put更新用户zxc
        request = put("/user")
                .contentType(MediaType.APPLICATION_JSON)
                .accept(MediaType.APPLICATION_JSON)
                .content("{\"id\":1,\"name\":\"zxc\",\"age\":20}");
        mvc.perform(request)
                .andExpect(status().isOk())
                .andDo(print())
                .andExpect(jsonPath("$.age").value(20))
                .andExpect(jsonPath("$.name").value("zxc"));
    }
}

上面例子涵盖了GETPOSTPUT 方法。在POST方法后面记得要设置content-typeaccept要不然有可能会失败。另外参数可以通过param来设置。返回的内容可以通过andExpect()来进行断言,判断这个接口返回的状态和内容是否与预期一样。如status().isOk()表示返回状态为200;content()表示返回的内容;jsonPath可以解释json对象,判断json里的内容是否和预期的一致。更多jsonPath用法可以看一下这里

正常情况上面这个测试用例运行是可以通过的,IDEA会显示一条绿色的进度条并输出1 test passed

发现异常

过一段时间后,我们可能会对UserController进行修改,比如把更新用户方法改成PUT /user/{id}

/**
* 更新用户
* @param user 用户信息
* @return
*/
@PutMapping("/user/{id}")
public User update(@PathVariable("id") long id, @RequestBody User user){
    user.setId(id);
    return userJpa.save(user);
}

这时候我们再运行这个测试用例时候IDEA会显示一条红色的进度条并输出1 test failed。看到这个提示我们便知道接口发生了变化与上次不一样了,这时候我们记得通知前端,告知他们我们接口发生了变更让他们记得修改过来。开会提到的问题得到解决。

在实际开发中我们并不需要每个测试类都去点一下让他运行。而是通过maven的test功能。maven install/package/test时候会执行所有@Test的代码,所以我们只要把测试类写好,在我们提交代码之前使用maven test 就可以得知我们有多少个接口发生了变化需要通知前端。

完整的代码可以到GitLab查看

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 136,470评论 19 139
  • Spring Boot 参考指南 介绍 转载自:https://www.gitbook.com/book/qbgb...
    毛宇鹏阅读 47,251评论 6 342
  • 一 阴雨绵绵的午后,微风轻拂,仿佛想把丝丝细雨吹送到更远更远的远方去。 凉飕飕的风拂过静谧的脸庞,她站在落地窗前,...
    Way青橙阅读 440评论 3 3
  • 我要从明天开始早起…… 我要从明天开始跑步…… 我要从明天开始读书…… 明日复明日,明日何其多, 我生待明日,万事...
    Miss墨菲阅读 614评论 5 7
  • 参考《风格与创造力》中设计的八种认知机制及功能,尝试解读写作的八种定义。 写作是解题活动。 写作是呈现写作者如何以...
    陈素封阅读 594评论 0 0

友情链接更多精彩内容