JUnit5学习之七:参数化测试(Parameterized Tests)进阶 (3)

在这里插入图片描述

进一步简化

回顾一下刚才用注解指定转换器的代码,如下图红框所示,您是否回忆起JUnit5支持自定义注解这一茬,咱们来把红框部分的代码再简化一下:

在这里插入图片描述


2. 新建注解类CsvToPerson.java,代码如下,非常简单,就是把上图红框中的@AggregateWith(PersonAggregator.class)搬过来了:

package com.bolingcavalry.parameterized.service.impl; import org.junit.jupiter.params.aggregator.AggregateWith; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.PARAMETER) @AggregateWith(PersonAggregator.class) public @interface CsvToPerson { }

再来看看上图红框中的代码可以简化成什么样子,直接用@CsvToPerson就可以将ArgumentsAccessor转为Person对象了:

@Order(20) @DisplayName("CsvSource的多个字段,通过指定聚合类转为Person实例(自定义注解)") @ParameterizedTest @CsvSource({ "Jane3, Doe3, BIG", "John3, Doe3, UNKNOWN" }) void customAggregatorAnnotationTest(@CsvToPerson Person person) { log.info("customAggregatorAnnotationTest [{}]", person); }

执行结果如下,可见和@AggregateWith(PersonAggregator.class)效果一致:

在这里插入图片描述

测试执行名称自定义

文章最后,咱们来看个轻松的知识点吧,如下图红框所示,每次执行测试方法,IDEA都会展示这次执行的序号和参数值:

在这里插入图片描述

其实上述红框中的内容格式也可以定制,格式模板就是@ParameterizedTest的name属性,修改后的测试方法完整代码如下,可见这里改成了中文描述信息:

@Order(21) @DisplayName("CSV格式多条记录入参(自定义展示名称)") @ParameterizedTest(name = "序号 [{index}],fruit参数 [{0}],rank参数 [{1}]") @CsvSource({ "apple3, 31", "banana3, 32", "'lemon3, lime3', 0x3A" }) void csvSourceWithCustomDisplayNameTest(String fruit, int rank) { log.info("csvSourceWithCustomDisplayNameTest, fruit [{}], rank [{}]", fruit, rank); }

执行结果如下:

在这里插入图片描述

至此,JUnit5的参数化测试(Parameterized)相关的知识点已经学习和实战完成了,掌握了这么强大的参数输入技术,咱们的单元测试的代码覆盖率和场景范围又可以进一步提升了;

你不孤单,欣宸原创一路相伴

Java系列

Spring系列

Docker系列

kubernetes系列

数据库+中间件系列

DevOps系列

欢迎关注公众号:程序员欣宸

微信搜索「程序员欣宸」,我是欣宸,期待与您一同畅游Java世界...
https://github.com/zq2599/blog_demos

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/wppfxg.html