springboot使用@SpringBootTest注解进行单元测试
一、示例
1.1 添加依赖
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>org.example</groupId> <artifactId>springboot-rabbitmq-fanout-producer</artifactId> <version>1.0-SNAPSHOT</version> <properties> <maven.compiler.source>8</maven.compiler.source> <maven.compiler.target>8</maven.compiler.target> </properties> <dependencyManagement> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-dependencies</artifactId> <version>2.3.2.RELEASE</version> <type>pom</type> <scope>import</scope> </dependency> </dependencies> </dependencyManagement> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> </dependency> </dependencies> </project>
1.2 application.yml
# 服务端口 server: port: 8080
1.3 主启动
package com; import javafx.application.Application; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class FanoutProducer { public static void main(String[] args) { SpringApplication.run(FanoutProducer.class, args); } }
1.4 业务类
package com.service; @Component public class OrderService { public void makeOrder() { System.out.println("测试成功!"); } }
1.5 单元测试类
package com.test; import com.service.OrderService; 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.SpringRunner; @RunWith(SpringRunner.class) @SpringBootTest public class FanoutProducerApplicationTests { @Autowired OrderService orderService; @Test public void contextLoads() throws Exception { orderService.makeOrder(); } }
Springboot的@RunWith(SpringRunner.class)注解的意义在于Test测试类要使用注入的类,比如@Autowired注入的类,有了@RunWith(SpringRunner.class)这些类才能实例化到spring容器中,自动注入才能生效,不然直接一个NullPointerExecption。 当然,你也许会看见有些人使用时,没有加上也可以正常使用,具体原因未知,可能是引用的依赖版本问题,视情况而定就行。
1.6 项目结构
二、版本说明
首先针对SpringBoot的测试类,2.2版本之前和2.2版本之后是不一样的,在2.2版本之前需要贴注解@SpringBootTest和@RunWith(SpringRunner.class)需要在Spring容器环境下进行测试,因为@Test导包的是org.junit.Test,而 在2.2版本之后只需要贴注解@SpringBootTest,@Test导包为org.junit.jupiter.api.Test
三、重要事项
创建的测试类必须在主启动类所在包路径同级下或其子级下,否则无法扫描到bean,且无法注入需要的bean,会报错
正确示例目录结构:
错误示例: