多参数@MethodSource参数化
- 通过@MethodSource注解引用方法作为参数化的数据源信息
- 在 @MethodSource 注解的参数必须是静态的工厂方法,除非测试类被注释为
@TestInstance(Lifecycle.PER_CLASS)
- 静态工厂方法的返回值需要和测试方法的参数对应
- 如果在 @MethodSource 注解中未指明方法名,会自动调用与测试方法同名的静态方法
测试方法参数对应的工厂方法返回值
@ParameterizedTest 方法 | 工厂方法 |
---|---|
void test(int) |
static int[] factory() |
void test(int) |
static IntStream factory() |
void test(String) |
static String[] factory() |
void test(String) |
static List<String> factory() |
void test(String) |
static Stream<String> factory() |
void test(String, String) |
static String[][] factory() |
void test(String, int) |
static Object[][] factory() |
void test(String, int) |
static Stream<Object[]> factory() |
void test(String, int) |
static Stream<Arguments> factory() |
void test(int[]) |
static int[][] factory() |
void test(int[]) |
static Stream<int[]> factory() |
void test(int[][]) |
static Stream<int[][]> factory() |
void test(Object[][]) |
static Stream<Object[][]> factory() |
- @MethodSource() 传入方法名称
- @MethodSource 不传入方法名称,找同名的方法
package com.mytest; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.MethodSource; import java.util.stream.IntStream; import java.util.stream.Stream; import static org.junit.jupiter.api.Assertions.assertNotEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; public class MethodSourceTest { @ParameterizedTest // 第一种在 @MethodSource 中指定方法名称 @MethodSource("stringProvider") void testWithLocalMethod(String argument) { assertNotNull(argument); } static Stream<String> stringProvider() { // 返回字符串流 return Stream.of("apple", "pear"); } @ParameterizedTest // 第二种在 @MethodSource 不指明方法名,框架会找同名的无参数方法 @MethodSource void testWithRangeMethodSource(Integer argument) { assertNotEquals(9, argument); } static IntStream testWithRangeMethodSource() { //int类型的数字流 return IntStream.of(1,2,3); } }
推荐使用下面的方法
package com.mytest; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.MethodSource; import java.util.stream.Stream; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.junit.jupiter.params.provider.Arguments.arguments; public class MultiMethodParamDemoTest { @ParameterizedTest // @MethodSource 不指明方法名,框架会找同名的无参数方法 @MethodSource // 多个参数和种类, 包含字符串、整型 void testWithMultiArgsMethodSource(String str, int num) { assertEquals(5, str.length()); assertTrue(num >= 2 && num <= 3); } static Stream<Arguments> testWithMultiArgsMethodSource() { // 返回 arguments(Object…) return Stream.of( arguments("apple", 2), arguments("pears", 3) ); } }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 单元测试从入门到精通
· 上周热点回顾(3.3-3.9)
· winform 绘制太阳,地球,月球 运作规律