Domanda

In Eclipse, while using the Parameterized runner in a junit test class, each run is noted by a number (0, 1, etc.)

Is there a way to replace this number with a proper label?

PS: I am using a JUNIT version 4.8 older than 4.11 so the @Parameters does not take any argument

Test Case:

@RunWith(value = Parameterized.class)
public class TestClass {

    @Parameters
    public static Collection<Object[]> getLabels() {
        List<Object[]> labels = new ArrayList<Object[]>();
        labels.add(new Object[] {"Toto"});
        labels.add(new Object[] {"Titi"});
        return labels;
    }

    private final String label;

    public TestClass(String label) {
        this.label = label;
    }

    @Test
    public void test1() {
        assertTrue(true);
    }
}

Result:

enter image description here

È stato utile?

Soluzione

There is an easy way to easily identify the individual test cases in a Parameterized test, you may provide a name using the @Parameters annotation.
This name is allowed to contain placeholders that are replaced at runtime:

{index}: the current parameter index
{0}, {1}, …: the first, second, and so on, parameter value

See example here: https://github.com/junit-team/junit/wiki/Parameterized-tests

Altri suggerimenti

Parameterized test is calling toString() internally, which does not work for us because some our implementations do not allow toString() and throw an exception.

In this case, the test names will be

TestClass
    testMethod
        [1] Argument1.toString()
        [2] Argument2.toString()
        [3]

I created an object wrapper for my argument that holds the original object, and overrides toString method.

Here is the example.

private static List<LabelArgument> getLabels() {
    List<LabelArgument> labels = new ArrayList<>();
    labels.add(LabelArgument.of(new SimpleLabel("Hi there")));
    labels.add(LabelArgument.of(new LabelExtended2D("Good bye!")));

    // Label toString throws an exception
    labels.add(LabelArgument.of(new Label("Simple"))); 

    return labels;
}

@ParameterizedTest
@MethodSource("getLabels")
void testLabel(LabelArgument labelArgument ) {
    var label = labelArgument.getLabel();
    // Do the test
}

private static class LabelArgument {

    private Label label;

    private LabelArgument(Label label) {
        this.label = label;
    }

    public static LabelArgument of(Label label) {
        return new LabelArgument(label);
    }

    @Override
    public String toString() {
        return label.getClass().getSimpleName();
    }
}

It will produce

TestClass
    testAllLabels
        [1] SimpleLabel
        [2] LabelExtended2D
        [3] Label
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top