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

我想改变默认的-[测试类]. runtest [n] -有意义的东西。


当前回答

你可以创建一个方法

@Test
public void name() {
    Assert.assertEquals("", inboundFileName);
}

虽然我不会一直用它,但弄清楚143到底是哪个测试数字还是很有用的。

其他回答

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

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

由于所访问的参数(例如“{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...
    );
}

您可能还想尝试JUnitParams: https://github.com/Pragmatists/JUnitParams

对于一个更复杂的对象,您可以执行以下操作(以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);
    }
}

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

在添加第三个参数之前,它是这样的

然后像这样

查看dsaff提到的JUnitParams,它使用ant在html报告中构建参数化测试方法描述。

这是在尝试LabelledParameterized并发现它虽然可以与eclipse一起工作,但就html报告而言,它不能与ant一起工作。

欢呼,