修改参数化测试的名称

226

在使用JUnit4中的参数化测试时,是否有一种方法可以设置自己的自定义测试用例名称?

我想将默认名称—[Test class].runTest[n]—更改为有意义的内容。

15个回答

2

一种解决方法是捕获并嵌套所有的Throwables到一个新的Throwable中,该Throwable包含有关参数的所有信息。该消息将出现在堆栈跟踪中。 这适用于所有断言、错误和异常失败的情况,因为它们都是Throwable的子类。

我的代码看起来像这样:

@RunWith(Parameterized.class)
public class ParameterizedTest {

    int parameter;

    public ParameterizedTest(int parameter) {
        super();
        this.parameter = parameter;
    }

    @Parameters
    public static Collection<Object[]> data() {
        return Arrays.asList(new Object[][] { {1}, {2} });
    }

    @Test
    public void test() throws Throwable {
        try {
            assertTrue(parameter%2==0);
        }
        catch(Throwable thrown) {
            throw new Throwable("parameter="+parameter, thrown);
        }
    }

}

失败测试的堆栈跟踪如下:

java.lang.Throwable: parameter=1
    at sample.ParameterizedTest.test(ParameterizedTest.java:34)
Caused by: java.lang.AssertionError
    at org.junit.Assert.fail(Assert.java:92)
    at org.junit.Assert.assertTrue(Assert.java:43)
    at org.junit.Assert.assertTrue(Assert.java:54)
    at sample.ParameterizedTest.test(ParameterizedTest.java:31)
    ... 31 more

0

由于访问参数(例如,使用"{0}")始终返回toString()的表示形式,一个解决方法是在每种情况下创建一个匿名实现并覆盖toString()。例如:

public static Iterable<? extends Object> data() {
    return Arrays.asList(
        new MyObject(myParams...) {public String toString(){return "my custom test name";}},
        new MyObject(myParams...) {public String toString(){return "my other custom test name";}},
        //etc...
    );
}

0

对于一个更复杂的对象,你可以采取以下操作(以 JUnit 4 为例):

@RunWith(Parameterized.class)
public class MainTest {
    private static Object[] makeSample(String[] array, int expectedLength) {
        return new Object[]{array, expectedLength, Arrays.toString(array)};
    }

    @Parameterized.Parameters(name = "for input {2} length should equal {1}")
    public static Collection<Object[]> data() {
        return Arrays.asList(
                makeSample(new String[]{"a"}, 1),
                makeSample(new String[]{"a", "b"}, 2)
        );
    }
    private final int expectedLength;
    private final String[] array;

    public MainTest(String[] array, int expectedLength, String strArray) {
        this.array = array;
        this.expectedLength = expectedLength;
    }

    @Test
    public void should_have_expected_length() {
        assertEquals(expectedLength, array.length);
    }
}

这里的技巧是使用一个输入参数作为字符串,描述输入的某个部分或整个测试用例。

在添加第三个参数之前,它看起来像这样enter image description here

之后就像这样

enter image description here


0

参数化测试在内部调用toString()。 如果您创建一个覆盖toString()的对象包装器,它将更改测试的名称。

这里有一个例子,我在其他帖子中回答了。 https://stackoverflow.com/a/67023556/1839360


0

像dsaff提到的那样,可以尝试使用JUnitParams,在html报告中使用ant构建参数化测试方法描述。

在尝试了LabelledParameterized后发现,虽然它可以在eclipse中工作,但就html报告而言,它与ant不兼容。

祝好!


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接