JUnit5常用注解的使用


Posted in Java/Android onJuly 02, 2021
目录
  • 20个注解
  • 元注解和组合注解
  • 小结
  • 参考资料:

注解(Annotations)是JUnit的标志性技术,本文就来对它的20个注解,以及元注解和组合注解进行学习。

20个注解

在org.junit.jupiter.api包中定义了这些注解,它们分别是:

@Test 测试方法,可以直接运行。

@ParameterizedTest 参数化测试,比如:

@ParameterizedTest
@ValueSource(strings = { "racecar", "radar", "able was I ere I saw elba" })
void palindromes(String candidate) {
    assertTrue(StringUtils.isPalindrome(candidate));
}

@RepeatedTest 重复测试,比如:

@RepeatedTest(10)
void repeatedTest() {
    // ...
}

@TestFactory 测试工厂,专门生成测试方法,比如:

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 测试模板,比如:

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 指定测试顺序,比如:

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每个测试方法生成一个实例,使用这个注解能让每个类只生成一个实例,比如:

@TestInstance(Lifecycle.PER_CLASS)
class TestMethodDemo {

    @Test
    void test1() {
    }

    @Test
    void test2() {
    }

    @Test
    void test3() {
    }

}

@DisplayName 自定义测试名字,会体现在测试报告中,比如:

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("?")
    void testWithDisplayNameContainingEmoji() {
    }

}

@DisplayNameGeneration 测试名字统一处理,比如:

import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.DisplayNameGeneration;
import org.junit.jupiter.api.DisplayNameGenerator;
import org.junit.jupiter.api.IndicativeSentencesGeneration;
import org.junit.jupiter.api.Nested;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;

class DisplayNameGeneratorDemo {

    @Nested
    @DisplayNameGeneration(DisplayNameGenerator.ReplaceUnderscores.class)
    class A_year_is_not_supported {

        @Test
        void if_it_is_zero() {
        }

        @DisplayName("A negative value for year is not supported by the leap year computation.")
        @ParameterizedTest(name = "For example, year {0} is not supported.")
        @ValueSource(ints = { -1, -4 })
        void if_it_is_negative(int year) {
        }

    }

    @Nested
    @IndicativeSentencesGeneration(separator = " -> ", generator = DisplayNameGenerator.ReplaceUnderscores.class)
    class A_year_is_a_leap_year {

        @Test
        void if_it_is_divisible_by_4_but_not_by_100() {
        }

        @ParameterizedTest(name = "Year {0} is a leap year.")
        @ValueSource(ints = { 2016, 2020, 2048 })
        void if_it_is_one_of_the_following_years(int year) {
        }

    }

}

@BeforeEach 在每个@Test, @RepeatedTest, @ParameterizedTest, or @TestFactory之前执行。

@AfterEach 在每个@Test, @RepeatedTest, @ParameterizedTest, or @TestFactory之后执行。

@BeforeAll 在所有的@Test, @RepeatedTest, @ParameterizedTest, and @TestFactory之前执行。

@AfterAll 在所有的@Test, @RepeatedTest, @ParameterizedTest, and @TestFactory之后执行。

@Nested 嵌套测试,一个类套一个类,例子参考上面那个。

@Tag 打标签,相当于分组,比如:

import org.junit.jupiter.api.Tag;
import org.junit.jupiter.api.Test;

@Tag("fast")
@Tag("model")
class TaggingDemo {

    @Test
    @Tag("taxes")
    void testingTaxCalculation() {
    }

}

@Disabled 禁用测试,比如:

import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Test;

@Disabled("Disabled until bug #99 has been fixed")
class DisabledClassDemo {

    @Test
    void testWillBeSkipped() {
    }

}
@Timeout 对于test, test factory, test template, or lifecycle method,如果超时了就认为失败了,比如:

class TimeoutDemo {

    @BeforeEach
    @Timeout(5)
    void setUp() {
        // fails if execution time exceeds 5 seconds
    }

    @Test
    @Timeout(value = 100, unit = TimeUnit.MILLISECONDS)
    void failsIfExecutionTimeExceeds100Milliseconds() {
        // fails if execution time exceeds 100 milliseconds
    }

}

@ExtendWith 注册扩展,比如:

@ExtendWith(RandomParametersExtension.class)
@Test
void test(@Random int i) {
    // ...
}

JUnit5提供了标准的扩展机制来允许开发人员对JUnit5的功能进行增强。JUnit5提供了很多的标准扩展接口,第三方可以直接实现这些接口来提供自定义的行为。

@RegisterExtension 通过字段注册扩展,比如:

class WebServerDemo {

    @RegisterExtension
    static WebServerExtension server = WebServerExtension.builder()
        .enableSecurity(false)
        .build();

    @Test
    void getProductList() {
        WebClient webClient = new WebClient();
        String serverUrl = server.getServerUrl();
        // Use WebClient to connect to web server using serverUrl and verify response
        assertEquals(200, webClient.get(serverUrl + "/products").getResponseStatus());
    }

}

@TempDir 临时目录,比如:

@Test
void writeItemsToFile(@TempDir Path tempDir) throws IOException {
    Path file = tempDir.resolve("test.txt");

    new ListWriter(file).write("a", "b", "c");

    assertEquals(singletonList("a,b,c"), Files.readAllLines(file));
}

元注解和组合注解

JUnit Jupiter支持元注解,能实现自定义注解,比如自定义@Fast注解:

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

import org.junit.jupiter.api.Tag;

@Target({ ElementType.TYPE, ElementType.METHOD })
@Retention(RetentionPolicy.RUNTIME)
@Tag("fast")
public @interface Fast {
}

使用:

@Fast
@Test
void myFastTest() {
    // ...
}

这个@Fast注解也是组合注解,甚至可以更进一步和@Test组合:

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

import org.junit.jupiter.api.Tag;
import org.junit.jupiter.api.Test;

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Tag("fast")
@Test
public @interface FastTest {
}

只用@FastTest就可以了:

@FastTest
void myFastTest() {
    // ...
}

小结

本文对JUnit20个主要的注解进行了介绍和示例演示,JUnit Jupiter支持元注解,可以自定义注解,也可以把多个注解组合起来。

参考资料:

https://junit.org/junit5/docs/current/user-guide/#writing-tests-annotations

https://vitzhou.gitbooks.io/junit5/content/junit/extension_model.html#概述

到此这篇关于JUnit5常用注解的使用的文章就介绍到这了,更多相关JUnit5注解内容请搜索三水点靠木以前的文章或继续浏览下面的相关文章希望大家以后多多支持三水点靠木!

Java/Android 相关文章推荐
Java8中接口的新特性使用指南
Nov 01 Java/Android
关于MybatisPlus配置双数据库驱动连接数据库问题
Jan 22 Java/Android
使用Java去实现超市会员管理系统
Mar 18 Java/Android
Android超详细讲解组件ScrollView的使用
Mar 31 Java/Android
SpringBoot中获取profile的方法详解
Apr 08 Java/Android
Java版 简易五子棋小游戏
May 04 Java/Android
利用正则表达式匹配浮点型数据
May 30 Java/Android
Spring Boot项目如何优雅实现Excel导入与导出功能
Jun 10 Java/Android
springboot实现string转json json里面带数组
Jun 16 Java/Android
SpringBoot项目部署到阿里云服务器的实现步骤
Jun 28 Java/Android
java中如何截取字符串最后一位
Jul 07 Java/Android
Java结构型设计模式之组合模式详解
Sep 23 Java/Android
解决Swagger2返回map复杂结构不能解析的问题
SpringBoot工程下使用OpenFeign的坑及解决
Jul 02 #Java/Android
SpringBoot读取Resource下文件的4种方法
Jul 02 #Java/Android
Java基础-封装和继承
Java 泛型详解(超详细的java泛型方法解析)
SpringBoot集成Druid连接池连接MySQL8.0.11
Java使用httpRequest+Jsoup爬取红蓝球号码
You might like
刚才在简化php的库,结果发现很多东西
2006/12/31 PHP
PHP 内存缓存加速功能memcached安装与用法
2009/09/03 PHP
PHP查询数据库中满足条件的记录条数(两种实现方法)
2013/01/29 PHP
PHP curl模拟登录带验证码的网站
2015/11/30 PHP
PHP实现APP微信支付的实例讲解
2018/02/10 PHP
Laravel5.1 框架Request请求操作常见用法实例分析
2020/01/04 PHP
禁止F5等快捷键的JS代码
2007/03/06 Javascript
JavaScript 精粹读书笔记(1,2)
2010/02/07 Javascript
JS滚轮事件onmousewheel使用介绍
2013/11/01 Javascript
jQuery实现的超酷苹果风格图标滑出菜单效果代码
2015/09/16 Javascript
JS实现滑动菜单效果代码(包括Tab,选项卡,横向等效果)
2015/09/24 Javascript
不得不分享的JavaScript常用方法函数集(上)
2015/12/23 Javascript
jquery 点击元素后,滚动条滚动至该元素位置的方法
2016/08/05 Javascript
AngularJS中$http服务常用的应用及参数
2016/08/22 Javascript
什么是JavaScript注入攻击?
2016/09/14 Javascript
Ionic3 UI组件之autocomplete详解
2017/06/08 Javascript
Angular4 反向代理Details实践
2018/05/30 Javascript
深入探讨JavaScript的最基本部分之执行上下文
2019/02/12 Javascript
ES6基础之展开语法(Spread syntax)
2019/02/21 Javascript
jQuery实现消息弹出框效果
2019/12/10 jQuery
Javascript新手入门之字符串拼接与变量的应用
2020/12/03 Javascript
[01:38]DOTA2 2015国际邀请赛中国区预选赛 Showopen
2015/06/01 DOTA
Python中操作mysql的pymysql模块详解
2016/09/13 Python
pygame游戏之旅 游戏中添加显示文字
2018/11/20 Python
linux 下python多线程递归复制文件夹及文件夹中的文件
2020/01/02 Python
如何通过python实现全排列
2020/02/11 Python
浅谈PyTorch的可重复性问题(如何使实验结果可复现)
2020/02/20 Python
python接口自动化之ConfigParser配置文件的使用详解
2020/08/03 Python
使用HTML5进行SVG矢量图形绘制的入门教程
2016/02/19 HTML / CSS
美国五金商店:Ace Hardware
2018/03/27 全球购物
木工主管岗位职责
2013/12/08 职场文书
共产党员批评与自我批评
2014/10/15 职场文书
《女娲补天》教学反思
2016/02/20 职场文书
HTML基础详解(下)
2021/10/16 HTML / CSS
MySQL表锁、行锁、排它锁及共享锁的使用详解
2022/04/02 MySQL
JS精髓原型链继承及构造函数继承问题纠正
2022/06/16 Javascript