JUnit – 参数化测试

在JUnit中,参数化测试是一种允许开发者使用不同的输入参数多次运行同一个测试方法的特性,以此来减少重复代码并提高测试效率。这种测试特别适合于验证一个方法在多种不同输入下的行为。JUnit 4和JUnit 5(JUnit Jupiter)都支持参数化测试,但实现方式有所不同。

JUnit 4 参数化测试

在JUnit 4中,你需要使用@RunWith(Parameterized.class)注解来标记测试类,并提供数据集和数据对应的测试逻辑。

import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameters;

@RunWith(Parameterized.class)
public class ParameterizedTestExample {

    private int input;
    private int expected;

    public ParameterizedTestExample(int input, int expected) {
        this.input = input;
        this.expected = expected;
    }

    @Parameters
    public static Collection<Object[]> data() {
        return Arrays.asList(new Object[][]{
                {1, 1},
                {2, 4},
                {3, 9},
                // 更多测试数据...
        });
    }

    @Test
    public void testSquare() {
        assertEquals(expected, calculateSquare(input));
    }

    private int calculateSquare(int num) {
        return num * num;
    }
}

JUnit 5 参数化测试

JUnit 5简化了参数化测试的语法,并提供了更灵活的数据提供方式。

import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.MethodSource;

public class ParameterizedTestExampleJupiter {

    @ParameterizedTest
    @MethodSource("data")
    public void testSquare(int input, int expected) {
        assertEquals(expected, calculateSquare(input));
    }

    static Stream<Arguments> data() {
        return Stream.of(
                Arguments.of(1, 1),
                Arguments.of(2, 4),
                Arguments.of(3, 9),
                // 更多测试数据...
        );
    }

    private int calculateSquare(int num) {
        return num * num;
    }
}

关键点总结

  • JUnit 4 使用@RunWith(Parameterized.class),并在类中定义一个带有参数的构造函数和一个静态方法(如@Parameters注解的方法)来提供数据集。
  • JUnit 5 引入了@ParameterizedTest注解和数据提供方法注解(如@MethodSource, @ValueSource, @CsvSource, @EnumSource等),使得测试方法和数据源的定义更加直观和灵活。

参数化测试是提高测试覆盖率和效率的有效手段,特别是在处理需要大量输入验证的场景时。

  • 6
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值