Junit5详解

Junit5是当前最新的测试框架。在junit5当中,一些之前使用的注解和测试方法被新的注解替换掉了。 使用junit5的测试结构如下:

import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Tag;
import org.junit.jupiter.api.Test;import com.howtodoinjava.junit5.examples.Calculator;public class AppTest {@BeforeAllstatic void setup(){System.out.println("@BeforeAll executed");}@BeforeEachvoid setupThis(){System.out.println("@BeforeEach executed");}@Tag("DEV")@Testvoid testCalcOne() {System.out.println("======TEST ONE EXECUTED=======");Assertions.assertEquals( 4 , Calculator.add(2, 2));}@Tag("PROD")@Disabled@Testvoid testCalcTwo() {System.out.println("======TEST TWO EXECUTED=======");Assertions.assertEquals( 6 , Calculator.add(2, 4));}@AfterEachvoid tearThis(){System.out.println("@AfterEach executed");}@AfterAllstatic void tear(){System.out.println("@AfterAll executed");}
}

主要有下面这些注解:@BeforeAll, @BeforeEach, @AfterAll, @AfterEach

@BeforeAll

JUnit 5 @BeforeAll注释是JUnit 4中@BeforeClass注释的替代。它用于表示应在当前测试类中的所有测试方法之前执行的带的方法。

@BeforeAll注释的方法必须是静态方法,否则会报运行时错误。

@BeforeEach

JUnit 5 @BeforeEach注释替代了JUnit 4中的@Before注释。被注释的方法会在当前类中的每个Test方法之前执行。也就是说有多少个test这个方法就会执行多少次

@BeforeEach注释的方法一定不能是静态方法,否则会报发运行时错误。

@AfterEach

JUnit 5 @AfterEach注释是JUnit 4中@After注释的替换。它用于表示应在当前类中的每个@Test方法之后执行带注释的方法。

@AfterAll

JUnit 5 @AfterAll注释是JUnit 4中@AfterClass注释的替换。它用于表示应在当前测试类中的所有测试之后执行带注释的方法。

@AfterAll注释的方法必须是静态方法,否则会报运行时错误。

junit5当中使用 @BeforeEach 替换了 @Before 使用 @AfterEach替换了 @After

@BeforeAll和@AfterAll用于非static方法的场景

在写测试尤其是基于spring boot的integration test的时候,我们常常需要通过注入的方式来初始化一些对象,当我们又想把这些对象在测试之前初始化时,就会发现对于注入的对象,只能将其放在非static的方法当中,根本原因在于spring的依赖注入实现原理。

但是将@beforeAll和@AfterAll放在非static方法上的时候却会报错。

为此,我们可以使用@TestInstance注解配置测试的生命周期。 如果我们不在测试类中声明它,则默认情况下,生命周期模式将为PER_METHOD。 因此,为了防止我们的测试类抛出JUnitException,我们可以使用@TestInstance(TestInstance.Lifecycle.PER_CLASS)对其进行注释。

例如:

@TestInstance(TestInstance.Lifecycle.PER_CLASS)
public class BeforeAndAfterAnnotationsUnitTest {String input;Long result;@BeforeAllpublic void setup() {input = "77";}@AfterAllpublic void teardown() {input = null;result = null;}@Testpublic void whenConvertStringToLong_thenResultShouldBeLong() {result = Long.valueOf(input);Assertions.assertEquals(77l, result);}
}

这样我们的测试就可以运行成功了。

@Disabled可以用于不运行某些test的场景。@Tag可以用于将测试分类。在这里不做展开