在JUnit 5测试方法中输入多个参数 [英] Feed multiple parameters in JUnit 5 test method

查看:97
本文介绍了在JUnit 5测试方法中输入多个参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想为我的代码库提供多态"测试用例.具体来说,Graph接口将有多种实现,并且希望针对所有接口(ALGraphAMGraph,...)重用测试代码.

I want to provide my codebase with "polymorphic" test cases. Specifically, there are going to be multiple implementations of a Graph interface and would like to reuse the test code for all of them (ALGraph, AMGraph, ...).

我想按照以下方式开发测试方法

I'd like to develop my test methods along the following lines

    @ParameterizedTest
    @MethodSource("graphFactory")
    // Note: JUnit 5 won't allow the following additional argument source
    @ValueSource(ints = {0, 31415, -31415})
    void testInsertDeleteNode(Graph g, Integer v) {
        g.insertNode(new Node<>(v));
        assertTrue(g.containsNode(new Node<>(v)));
        assertEquals(1, g.vertices().size());

        g.deleteNode(new Node<>(v));
        assertFalse(g.containsNode(new Node<>(v)));
        assertEquals(0, g.vertices().size());
    }

但是JUnit的构建方式阻止了我完成此方案.

but the way JUnit is built is preventing me from accomplishing this scheme.

因此,基本上,我想为测试提供多个参数的笛卡尔积.可以使用现成的参数提供程序(ValueSourceNullSource,...)还是我是否需要借助@MethodSource来强制设置自定义的参数提供程序?

So basically I'd like to provide a cartesian product of multiple arguments to my tests. Is that possible with the out-of-the-box argument providers (ValueSource, NullSource, ...) or do I forcibly need to set up customized ones with the aid of @MethodSource?

推荐答案

开箱即用不支持该功能,但是

It's not supported out of the box -- but there already exists a feature request at https://github.com/junit-team/junit5/issues/1427

在此处查找示例和概念验证解决方案:

Find an example and proof of concept solution here: https://github.com/junit-team/junit5-samples/tree/master/junit5-jupiter-extensions

@CartesianProductTest({"0", "1"})
void threeBits(String a, String b, String c) {
    int value = Integer.parseUnsignedInt(a + b + c, 2);
    assertTrue((0b000 <= value) && (value <= 0b111));
}

@CartesianProductTest
@DisplayName("S ⨯ T ⨯ U")
void nFold(String string, Class<?> type, TimeUnit unit, TestInfo info) {
    assertTrue(string.endsWith("a"));
    assertTrue(type.isInterface());
    assertTrue(unit.name().endsWith("S"));
    assertTrue(info.getTags().isEmpty());
}

static CartesianProductTest.Sets nFold() {
    return new CartesianProductTest.Sets()
            .add("Alpha", "Omega")
            .add(Runnable.class, Comparable.class, TestInfo.class)
            .add(TimeUnit.DAYS, TimeUnit.HOURS);
}

产生一个测试计划,例如:

Yields a test plan like:

这篇关于在JUnit 5测试方法中输入多个参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆