springboot中junit的使用以及JUnit 4和JUnit 5区别

在Spring Boot 2.2.X以后使用Junit5

import org.junit.jupiter.api.Test;

在Spring Boot 2.2.x之前使用Junit4

import org.junit.Test;

Spring Boot 2.2.X之后的Junit5

spring-boot-starter-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>

Junit5测试类

import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest
class DemoApplicationTests {@Testvoid contextLoads() {}
}

Spring Boot 2.2.X之前的Junit4

spring-boot-starter-test工件的依赖配置

<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-test</artifactId><scope>test</scope>
</dependency>

Junit4测试类

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
@RunWith(SpringRunner.class)
@SpringBootTest
public class Demo1ApplicationTests {@Testpublic void contextLoads() {}
}

JUnit 4和JUnit 5区别

1.public修饰符
JUnit 4单元测试的类和方法必须是public的
2.JDK版本
Junit 4需要Java 5或更高版本
Junit 5需要Java 8或更高版本
3.组件不同
JUnit 4组件内容集中在一个junit.jar中
Junit 5由3个子项目组成,即JUnit Platform,JUnit Jupiter和JUnit Vintage(此项目可以支持在JUnit 5平台上运行JUnit 3和JUnit 4编写的测试)。
4.注解的使用不同

junit4junit5说明
@Test@Test定义测试方法即测试用例
@BeforeClass@BeforeAll在当前类中的所有测试方法之前执行
@AfterClass@AfterAll在当前类中的所有测试方法之后执行
@Before@BeforeEach在每个测试用例前执行
@After@AfterEach在每个测试用例后执行
@Ignore@Disabled禁用测试方法或类
@Category@Tag标记和过滤
@NA@TestFactory测试工厂进行动态测试
@NA@Nested嵌套测试
@NA@ExtendWith注册自定义扩展


本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场,不承担相关法律责任。如若转载,请注明出处。 如若内容造成侵权/违法违规/事实不符,请点击【内容举报】进行投诉反馈!

相关文章

立即
投稿

微信公众账号

微信扫一扫加关注

返回
顶部