注:文章皆为个人纪录,可用性请以最终结果为准,若有错还请大佬们指出,谢谢!
方式一:org.junit.Test;
缺点:
无法进行依赖注入,运行时注入的对象为null
优点:
方便,随用随删
1. 导入依赖:
<!-- https://mvnrepository.com/artifact/junit/junit -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.13.2</version>
</dependency>
2. 随便找个Java文件开始写测试方法
import org.junit.Test;
@Resource
private IPaymentService iPaymentService;
@Test
public void test() {
System.out.println("#################### 测试开始");
List<Payment> list = iPaymentService.list();
System.out.println(list);
}
响应:
方式二:org.springframework.boot.test.context.SpringBootTest;
优点:
真实测试代码运行是否可行,可编译,可注入
缺点:
麻烦,需要创建测试案例
1. 在模块的 src 目录下右键选择 Directory 创建文件
2. 在弹窗中选择 test\java
3. 创建该模块下的测试基类 ApplicationTests
3.1 在 test.java 目录 下创建一个类 ApplicationTests
3.2 在ApplicationTests类上添加注解并指定启动类(每个模块一个测试基类)
@SpringBootTest(classes = 启动类.class)
4. 创建测试类,继承测试基类 ApplicationTests
import org.junit.jupiter.api.Test;
public class Test1 extends ApplicationTests {
@Resource
private IPaymentService iPaymentService;
@Test
public void test1() {
System.out.println("#################### 测试开始");
List<Payment> list = iPaymentService.list();
System.out.println(CollectionUtil.isEmpty(list));
}
}
响应:
#################### 测试开始
false
总结:
测试方法中不需要调用spring注入的对象,使用方式一,反之使用方式二