枚举参数的参数化@EnumSource
- 使用枚举类作为测试数据。
- 枚举参数参数化注解 @EnumSource。
- 必须与 @ParameterizedTest 结合使用。
需要添加@EnumSource
注解
测试方法传入枚举类作为参数
package com.mytest; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.EnumSource; import java.util.EnumSet; import static org.junit.jupiter.api.Assertions.assertTrue; public class EnumTest { // 创建一个枚举类 public enum HogwartsUnit { Harry("Harry", 18), AD("AD", 19); private final String name; private final Integer age; private HogwartsUnit(String name, Integer age){ this.name = name; this.age = age; } } @ParameterizedTest // @EnumSource 注解表示使用枚举类型 @EnumSource // 枚举类作为参数传入测试方法 void testWithEnumSourceInclude(HogwartsUnit unit) { assertTrue(EnumSet.of(HogwartsUnit.Harry, HogwartsUnit.AD).contains(unit)); } }
通过 names 参数指定枚举值
import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.EnumSource; import java.util.EnumSet; import static org.junit.jupiter.api.Assertions.assertTrue; public class EnumTest { // 创建一个枚举类 public enum HogwartsUnit { Harry("Harry", 18), AD("AD", 19); private final String name; private final Integer age; private HogwartsUnit(String name, Integer age){ this.name = name; this.age = age; } } @ParameterizedTest // @EnumSource 注解表示使用枚举类型, // 通过 names 参数指定使用的枚举值 @EnumSource(names = {"Harry"}) // 枚举类作为参数传入测试方法 void testWithEnumSourceInclude(HogwartsUnit unit) { assertTrue(EnumSet.of(HogwartsUnit.Harry, HogwartsUnit.AD).contains(unit)); } }
- mode 参数指定规则
- EXCLUDE 代表取反,即指定名称不等于的场景
- MATCH_ALL 代表通过正则进行匹配
package com.mytest; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.EnumSource; import java.util.EnumSet; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.junit.jupiter.params.provider.EnumSource.Mode.EXCLUDE; import static org.junit.jupiter.params.provider.EnumSource.Mode.MATCH_ALL; public class EnumTest2 { // 创建一个枚举类 public enum HogwartsUnit { Harry("Harry", 18), AD("AD", 19); private final String name; private final Integer age; private HogwartsUnit(String name, Integer age){ this.name = name; this.age = age; } } @ParameterizedTest // @EnumSource 注解表示使用枚举类型, // 通过 mode 参数指定规则 // mode 值为 EXCLUDE 代表取反,即指定名称不为Harry的枚举值 @EnumSource(mode = EXCLUDE, names = {"Harry"}) // 枚举类作为参数传入测试方法 void testWithEnumSourceExclude(HogwartsUnit unit) { assertTrue(EnumSet.of(HogwartsUnit.Harry, HogwartsUnit.AD).contains(unit)); } @ParameterizedTest // @EnumSource 注解表示使用枚举类型, // 通过 mode 参数指定规则 // mode 值为 EXCLUDE 代表取反,即指定名称不为Harry的枚举值 @EnumSource(mode = MATCH_ALL, names = {".*ry"}) // 枚举类作为参数传入测试方法 void testWithEnumSourceRegex(HogwartsUnit unit) { assertTrue(unit.name().endsWith("ry")); } }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 单元测试从入门到精通
· 上周热点回顾(3.3-3.9)
· winform 绘制太阳,地球,月球 运作规律