注解(Annotations)是JUnit的標志性技術,本文就來對它的20個注解,以及元注解和組合注解進行學習。
20個注解
在org.junit.jupiter.api包中定義了這些注解,它們分別是:
@Test 測試方法,可以直接運行。
@ParameterizedTest 參數化測試,比如:
1
2
3
4
5
|
@ParameterizedTest @ValueSource (strings = { "racecar" , "radar" , "able was I ere I saw elba" }) void palindromes(String candidate) { assertTrue(StringUtils.isPalindrome(candidate)); } |
@RepeatedTest 重復測試,比如:
1
2
3
4
|
@RepeatedTest ( 10 ) void repeatedTest() { // ... } |
@TestFactory 測試工廠,專門生成測試方法,比如:
1
2
3
4
5
6
7
8
9
|
import org.junit.jupiter.api.DynamicTest; @TestFactory Collection<DynamicTest> dynamicTestsFromCollection() { return Arrays.asList( dynamicTest( "1st dynamic test" , () -> assertTrue(isPalindrome( "madam" ))), dynamicTest( "2nd dynamic test" , () -> assertEquals( 4 , calculator.multiply( 2 , 2 ))) ); } |
@TestTemplate 測試模板,比如:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
|
final List<String> fruits = Arrays.asList( "apple" , "banana" , "lemon" ); @TestTemplate @ExtendWith (MyTestTemplateInvocationContextProvider. class ) void testTemplate(String fruit) { assertTrue(fruits.contains(fruit)); } public class MyTestTemplateInvocationContextProvider implements TestTemplateInvocationContextProvider { @Override public boolean supportsTestTemplate(ExtensionContext context) { return true ; } @Override public Stream<TestTemplateInvocationContext> provideTestTemplateInvocationContexts( ExtensionContext context) { return Stream.of(invocationContext( "apple" ), invocationContext( "banana" )); } } |
@TestTemplate必須注冊一個TestTemplateInvocationContextProvider,它的用法跟@Test類似。
@TestMethodOrder 指定測試順序,比如:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
|
import org.junit.jupiter.api.MethodOrderer.OrderAnnotation; import org.junit.jupiter.api.Order; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.TestMethodOrder; @TestMethodOrder (OrderAnnotation. class ) class OrderedTestsDemo { @Test @Order ( 1 ) void nullValues() { // perform assertions against null values } @Test @Order ( 2 ) void emptyValues() { // perform assertions against empty values } @Test @Order ( 3 ) void validValues() { // perform assertions against valid values } } |
@TestInstance 是否生成多個測試實例,默認JUnit每個測試方法生成一個實例,使用這個注解能讓每個類只生成一個實例,比如:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
@TestInstance (Lifecycle.PER_CLASS) class TestMethodDemo { @Test void test1() { } @Test void test2() { } @Test void test3() { } } |
@DisplayName 自定義測試名字,會體現在測試報告中,比如:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
|
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 ( "
延伸 · 閱讀
精彩推薦
|