JUnit5编写基本测试
JUnit5的测试不是通过名称,而是通过注解来标识的。
测试类与方法
Test Class:测试类,必须包含至少一个test方法,包括:
- 最外层的class
-
static
member class -
@Nested
class
Test Method:测试方法,包括:
@Test
@RepeatedTest
@ParameterizedTest
@TestFactory
@TestTemplate
Lifecycle Method:生命周期方法,包括:
@BeforeAll
@AfterAll
@BeforeEach
@AfterEach
注意:
- Test Method和Lifecycle Method不能是
abstract
,也不能return。它们可以在当前测试类中声明,也可以继承自父类或接口。 - Test class、Test Method和Lifecycle Method都不能是private。
示例代码:
import static org.junit.jupiter.api.Assertions.fail;
import static org.junit.jupiter.api.Assumptions.assumeTrue;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Test;
class StandardTests {
@BeforeAll
static void initAll() {
}
@BeforeEach
void init() {
}
@Test
void succeedingTest() {
}
@Test
void failingTest() {
fail("a failing test");
}
@Test
@Disabled("for demonstration purposes")
void skippedTest() {
// not executed
}
@Test
void abortedTest() {
assumeTrue("abc".contains("Z"));
fail("test should have been aborted");
}
@AfterEach
void tearDown() {
}
@AfterAll
static void tearDownAll() {
}
}
自定义显示名字
Test class和test method可以使用@DisplayName
自定义在测试报告中的显示名字,支持空格、特殊字符和emoji表情符号。
示例:
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
@DisplayName("A special test case")
class DisplayNameDemo {
@Test
@DisplayName("Custom test name containing spaces")
void testWithDisplayNameContainingSpaces() {
}
@Test
@DisplayName("╯°□°)╯")
void testWithDisplayNameContainingSpecialCharacters() {
}
@Test
@DisplayName("