Junit 4 与Junit 5区别

it2023-03-04  74

所需JDK

Junit 4Junit 5需要 Java 5 或以上版本需要Java 8 或以上版本

Architecture

Junit 4 所有的东西在一个jar包里,maven依赖如下:

<dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.13.1</version> <scope>test</scope> </dependency>

Junit 5 由JUnit Platform, JUnit Jupiter 和 JUnit Vintage 三个子项目组成:

JUnit Platform 定义了 test engine API,用于开发在平台上运行新测试框架JUnit Jupiter:包含所有注解,有 TestEngine 实现来运行用这些注解编写的测试用例。JUnit Vintage 用JUnit 3 和 JUnit 4写的测试用例可以在JUnit 5 Platform上运行

注解

说明Junit 4Junit 5定义测试方法即用例@Test@Test在当前类中的所有测试方法之前执行@BeforeClass@BeforeAll在当前类中的所有测试方法之后执行@AfterClass@AfterAll在每个测试用例前执行@Before@BeforeEach在每个测试用例后执行@After@AfterEach禁用测试方法或类@Ignore@DisabledTagging 和 filtering@Category@Tag

断言

Junit 4 :org.junit.Assert Junit 5:org.junit.jupiter.Assertions

Assumptions

Junit 4 :org.junit.Assume ,有如下5个方法:

assumeFalse() assumeNoException() assumeNotNull() assumeThat() assumeTrue()

Junit 5:org.junit.jupiter.api.Assumptions ,有如下三个方法:

assumeFalse() assumingThat​() assumeTrue()

Test Suites

Junit 4 用@RunWith 和 @Suite 注解:

import org.junit.runner.RunWith; import org.junit.runners.Suite; @RunWith(Suite.class) @Suite.SuiteClasses({ ExceptionTest.class, TimeoutTest.class }) public class JUnit4Example { }

Junit 5 用@RunWith, @SelectPackages 和 @SelectClasses,如下:

import org.junit.platform.runner.JUnitPlatform; import org.junit.platform.suite.api.SelectPackages; import org.junit.runner.RunWith; @RunWith(JUnitPlatform.class) @SelectPackages("junit5.examples") public class JUnit5Example { }

第三方集成

在JUnit4中,没有对第三方插件和IDE的集成支持。他们必须依靠reflection

JUnit5为此有专门的子项目,即JUnit platform,它定义了TestEngine API,用于开发在该平台上运行的测试框架

参考:https://howtodoinjava.com/junit5/junit-5-vs-junit-4/

最新回复(0)