多参数@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)
        );
    }
}

 

posted @ 2023-08-23 23:07  Mr_sven  阅读(224)  评论(0编辑  收藏  举报