一、JUnit4 与 JUnit 5 常用注解对比
JUnit 5旨在调整java 8样式的编码,并且比JUnit 4更强大和灵活。在这篇文章中,JUnit 5 vs JUnit 4,我们将关注junit 4和junit 5之间的一些主要差异。
JUnit4JUnit5说明@Test@Test表示该方法是一个测试方法。
@BeforeClass@BeforeAll在当前类中的所有测试方法之前执行
@AfterClass@AfterAll在当前类中的所有测试方法之后执行
@Before@BeforeEach在每个测试方法之前执行
@After@AfterEach在每个测试方法之后执行
@Ignore@Disabled用于禁用一个测试类或测试方法
@Category@Tag标记和过滤
@Parameters@ParameterizedTest表示该方法是一个参数化测试
@RunWith@ExtendWith@Runwith就是放在测试类名之前,用来确定这个类怎么运行的
N/A@ExtendWith注册自定义扩展
N/A@TestFactory测试工厂进行动态测试
N/A@Neste嵌套测试
二、JUnit 5和JUnit 4之间的其他差异
1、构建
JUnit 4将所有内容捆绑到单个jar文件中。
与以前版本的JUnit不同,JUnit 5由三个不同子项目中的几个不同模块组成。JUnit 5 = JUnit Platform + JUnit Jupiter + JUnit Vintage
JUnit Platform:是基于JVM的运行测试的基础框架,它定义了开发运行在这个测试框架上的TestEngine API。此外该平台提供了一个控制台启动器,可以从命令行启动平台,可以为Gradle和 Maven构建插件,同时提供基于JUnit 4的Runner。
JUnit Jupiter:是在JUnit 5中编写测试和扩展的新编程模型和扩展模型的组合.Jupiter子项目提供了一个TestEngine在平台上运行基于Jupiter的测试。
JUnit Vintage:提供了一个TestEngine在平台上运行基于JUnit 3和JUnit 4的测试。
2、必需的JDK版本Junit 4需要Java 5或更高版本。
Junit 5需要Java 8或更高版本。
3、断言
在Junit 4中,org.junit.Assert具有所有断言方法来验证预期结果和结果。
它们接受错误消息的额外参数作为方法签名中的FIRST参数。例如public static void assertEquals(long expected, long actual)
public static void assertEquals(String message, long expected, long actual)
在JUnit 5中,org.junit.jupiter.Assertions包含大多数断言方法,包括附加assertThrows()和assertAll()方法。assertAll()到目前为止处于实验状态,并用于分组断言。
JUnit 5断言方法也有重载方法,以支持在测试失败时传递错误消息,例如public static void assertEquals(long expected, long actual)
public static void assertEquals(long expected, long actual, String message)
public static void assertEquals(long expected, long actual, Supplier messageSupplier)
4、假设
在Junit 4中,org.junit.Assume 包含用于说明测试有意义的条件的假设的方法。它有以下五种方法:assumeFalse ()
assumeNoException ()
assumeNotNull ()
assumingThat ()
assumeTrue ()
在Junit 5中,org.junit.jupiter.api.Assumptions 包含用于说明测试有意义的条件的假设的方法。它有以下三种方法:assumeFalse ()
assumeTrue ()
assumingThat ()
5、标记和过滤在Junit 4中,使用了@category注释。
在Junit 5中,使用了@tag注释。
6、测试套房
在JUnit 4,@RunWith和@Suite注释。例如import org.junit.runner.RunWith;
import org.junit.runners.Suite;
@RunWith(Suite.class)
@Suite.Suite
Classes({
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("com.howtodoinjava.junit5.examples")
public class JUnit5Example{
}
7、第三方整合
在Junit 4中,没有对第三方插件和IDE的集成支持。他们必须依靠反射。
JUnit 5为此专门设立了子项目,即JUnit平台。它定义了TestEngine用于开发在平台上运行的测试框架的API。
参考
JUnit 5和JUnit 4比较:https://blog.csdn.net/u010675669/article/details/86574956
JUnit 5 新特性:https://www.ibm.com/developerworks/cn/java/j-junit5/