JUnit 5
- 依赖
原文:
The starter also brings the vintage engine so that you can run both JUnit 4 and JUnit 5 tests. If you have migrated your tests to JUnit 5, you should exclude JUnit 4 support.
springboot2.2.x之后支持JUnit 5,需要的依赖是
<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>
- 测试类:
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest
class JunitTest {
@Test
void testJunit5(){
System.out.println("junit5");
}
}
PS:
@Test
的包是org.junit.jupiter.api.Test
- 不需要
@RunWith(SpringRunner.class)
,原文:
If you are using JUnit 4, don’t forget to also add @RunWith(SpringRunner.class) to your test, otherwise the annotations will be ignored. If you are using JUnit 5, there’s no need to add the equivalent @ExtendWith(SpringExtension.class) as @SpringBootTest and the other @…Test annotations are already annotated with it.
- 测试类和测试方法不需要
public
修饰
JUnit 4
- 依赖
springboot2.2.x之前支持JUnit 4,需要的依赖是
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
- 测试类
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
@SpringBootTest
@RunWith(SpringRunner.class)
public class JunitTest {
@Test
public void testJunit4(){
System.out.println("junit4");
}
}
PS:
@Test
的包是org.junit.Test
- 需要
@RunWith(SpringRunner.class)
- 测试类和测试方法需要
public
修饰
InvalidTestClassError
当JUnit 4和JUnit 5混用时会报改错误,比如依赖导错、Java包导错、public修饰问题等。