注解(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 ( "
声明:本文来自网络,不代表【好得很程序员自学网】立场,转载请注明出处:http://www.haodehen.cn/did214602
阅读:8次
|