samedi 28 mars 2020

JUnit 5 Extension - Get parameter index

I am writing a JUnit5 extension and I need to get the current parameter index of a @ParameterizedTest.

For example, in the following test:

@ParameterizedTest
@ValueSource(ints = {1, 3, 5, -3, 15, Integer.MAX_VALUE})
void shouldReturnTrueForOddNumbers(int number) {
    assertTrue(Numbers.isOdd(number));
}

When the test runs with the value 1, the extension should get index 1, when it runs with value 3, index 2, and so on.

I didn't find a straightforward way to do it. As an alternative, I wrote two solutions:

1 - Using the display name. Source code

private int extractIndex(ExtensionContext context) {
    String patternString = "\\[(\\d+)\\]";
    Pattern pattern = Pattern.compile(patternString);
    Matcher matcher = pattern.matcher(context.getDisplayName());
    if (matcher.find()) {
        return Integer.valueOf(matcher.group(1));
    } else {
        return 0;
    }
}

2 - Using reflection. Source code

    private int extractIndex(ExtensionContext context) {
        Method method = ReflectionUtils.findMethod(context.getClass(),
                "getTestDescriptor").orElse(null);
        TestTemplateInvocationTestDescriptor descriptor =
                (TestTemplateInvocationTestDescriptor)
                        ReflectionUtils.invokeMethod(method, context);

        try {
            Field indexField = descriptor.getClass().getDeclaredField("index");
            indexField.setAccessible(true);
            return Integer.parseInt(indexField.get(descriptor).toString());
        } catch (NoSuchFieldException | IllegalAccessException e) {
            throw new RuntimeException(e);
        }
    }

In this repository, I have put examples using both solutions.

Is there a better way of achieving it?





Aucun commentaire:

Enregistrer un commentaire