【1】最重要的一点:测试类启动依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
</dependency>
【2】问题重点:
springboot的版本,限定了Test的版本,导致在测试类有时候会出现问题。最明显的表现就是我们在使用测试类的时候,有时候需要添加@RunWith注解,有时候不需要
【3】实用总结
-
[1] JUnit4版本的@Test,需要加**@RunWith(SpringRunner.class)**
导入的依赖是org.junit.Test + org.junit.runner.RunWith

-
[2] JUnit5版本的@Test,不需要加@RunWith
导入的依赖是org.junit.jupiter.api.Test

-
[3] 测试类应该和启动类在同一个工程,同时相对路径要一样,不然的话需要在测试类的启动注解中标明启动类→@SpringBootTest(classes={启动类.class})

【4】@RunWith啥时候使用呢?
-
springboot版本2.4之后,只支持JUnit5,不支持JUnit4,无需添加@RunWith
-
springboot版本2.2-2.4,默认使用JUnit5,同时兼容JUnit4.所以如果添加@RunWith,那么在使用@Test注解导入依赖的时候记得导入org.junit.Test;如果不添加@RunWIth,那么在使用@Test注解导入依赖的时候记得导入org.junit.jupiter.api.Test
⇒可以在使用注解@Test注解的时候,排除掉JUnit4的干扰,这样导入依赖的时候就不会出现下面的情况,导致有有时候导包错误

JUnit4中使用的测试引擎是junit-vintage-engine
JUnit5中使用的测试引擎是junit-jupiter-engine
排除JUnit4的方式,就是在test的启动器中排除掉对应的测试引擎。
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>
-
springboot版本2.2之前,只支持JUnit4,需要添加注解@RunWith(SpringRunner.class)
注意:如果不加@RunWith,只引入JUnit5的依赖,那么可能会导致测试类可以启动但是无法正常使用的问题。例如@Autowired无法注入。所以对于springboot2.2之前的测试类在使用时无比加上注解@RunWith(SpringRunner.class)