文章目录
参考资料
运行环境
- win10
- IDEA专业版
- SpringBoot 2.6.2
一、SpringBoot 整合 Junit
案例需求:SpringBoot整合Junit
案例实现步骤:
- 搭建SpringBoot工程
- 引入starter-test起步依赖
- 编写测试类
- 添加测试相关注解
- @RunWith(SpringRunner.class)
- @SpringBootTest(classes = 启动类.class)
- 编写测试方法
1.1 构建项目
1.2 test起步依赖
在IDEA创建项目SpringBoot Web项目后 pom.xml 自带的 Junit起步依赖为:
pom.xml
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<scope>test</scope>
</dependency>
1.3 模拟业务逻辑层
UserService 模拟 Service层的业务逻辑
UserService.java
package com.uni.springboottest;
import org.springframework.stereotype.Service;
@Service
public class UserService {
public void add(){
System.out.println("add..");
}
}
测试方法有两个包,一个是springboottest、另一个是普通的test
它们区别在于,前者的包名跟 SpringBoot Application的包名一致,这种情况下在使用注解标记@SpringBootTest类时就无需指定类,代码如下:
springboottest/UserServiceTest.java
package com.uni.springboottest;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4