IDEA + Spring boot 单元测试

1. 创建测试类

打开IDEA,在任意类名,任意接口名上,按ctrl+shift+t选择Create New Test


image

然后根据提示操作(默认即可),点击确认,就在项目的/test/java下的对应包里,生成了与类对应的测试类。
如果没有“Create New Test”,请更新idea版本或者安装JUnitGenerator V2.0

1.1 安装JUnitGenerator V2.0

注意,本步骤是找不到那个“Create New Test”,再做的操作!
在左上角点击File,选择settings,在列表中选择Plugins,在[搜索框],如果未安装会有install绿色按钮。点击下载。如图:


image

然后重启IDEA。

2. spring-boot-test介绍

先确认项目是否引入依赖(一般都已经引用了)

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-test</artifactId>
</dependency>

在生成的测试类中就可以写单元测试了。用spring自带spring-boot-test的测试工具类即可,
spring-boot-starter-test 启动器能引入这些 Spring Boot 测试模块:

  • JUnit:Java 应用程序单元测试标准类库。
  • Spring Test & Spring Boot Test:Spring Boot 应用程序功能集成化测试支持。
  • Mockito:一个Java Mock测试框架。
  • AssertJ:一个轻量级的断言类库。
  • Hamcrest:一个对象匹配器类库。
  • JSONassert:一个用于JSON的断言库。
  • JsonPath:一个JSON操作类库。

如果对单元测试以及Mock测试不甚了解,请参考我的另一篇博文:
https://www.jianshu.com/p/37de454c5f34
或自行百度搜索。

3. 示例代码

// TODO...

原文地址:https://www.jianshu.com/p/043f1d622e61

猜你喜欢

转载自www.cnblogs.com/jpfss/p/10954685.html