JUnit5是什么
官网介绍如下 :JUnit 5 is the next generation of JUnit. The goal is to create an up-to-date foundation for developer-side testing on the JVM. This includes focusing on Java 8 and above, as well as enabling many different styles of testing.JUnit 5 is the result of JUnit Lambda and its crowdfunding campaign on Indiegogo.
主要就是说Junit5基于Java8及以上,实现时用到了许多Java8的特性比如Lambda表达式和接口默认方法等
JUnit5分为以下三个模块
1. JUnit Platform
JUnit platform的职责
- 加载测试框架到JVM
- 定义了 TestEngine API 来对测试框架进行扩展
- 提供了 Console Launcher来支持命令行和 Maven以及Gradle的插件
关键类 : TestEngine、Launcher
2. JUnit Jupiter
提供了JUnit5的编程模型和扩展模型提供了一个TestEngine的实现(JupiterTestEngine)来跑基于Jupiter的测试
3.Junit Vintage
用来跑JUnit低版本的测试用例,保证向下兼容
JUnit5的annotation
JUnit5所有的annotation都放在org.junit.jupiter.api包下
1.和JUnit4等价的注解
- @Disabled == @Ignore
- @BeforeEach == @Before 、 @AfterEach == @After
- @BeforeAll == @BeforeClass、 @AfterAll == @AfterClass
2. JUnit5新增的注解
1. @DisplayName : 设置测试类或测试方法的展示内容,在最终结果打印出来时可以看到,内容可以是文本甚至是emoji
@Test @DisplayName("╯°□°)╯") void testWithDisplayNameContainingEmoji() { }
2.@TestInstance : 定义在类上面,用于控制测试类的实例是否是单例的,即该实例是否被该类的所有测试方法共享,即PER_CLASS和PER_METHOD两种模式,定义如下
@Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME) @Inherited @Documented @API(status = STABLE, since = "5.0") public @interface TestInstance
3. @ExtendWith:对测试类进行扩展,基于java SPI机制,接口为Extension,作为@Runwith的替代,典型的实现有SpringExtension、MockitoExtension
4. @ParameterizedTest:参数化测试,表示测试方法可以带有参数了
@ParameterizedTest @ValueSource(strings = { "Hello", "World" }) void testWithStringParameter(String argument) { assertNotNull(argument); }
5. @Tag:给类或者方法打标签,用于进行过滤,类似JUnit4中Categories的概念,可以新定义annotation来达到复制@Tag的效果
@Target({ ElementType.TYPE, ElementType.METHOD }) @Retention(RetentionPolicy.RUNTIME) @Tag("fast") public @interface Fast { }