junit报错:org.junit.runners.model.InvalidTestClassError

JUnit 5

  1. 依赖

原文:

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>
  1. 测试类:
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

  1. 依赖

springboot2.2.x之前支持JUnit 4,需要的依赖是

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-test</artifactId>
    <scope>test</scope>
</dependency>
  1. 测试类
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修饰问题等。

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值