Расширение JUnit 5 - Получить индекс параметра - PullRequest
0 голосов
/ 28 марта 2020

Я пишу расширение JUnit5, и мне нужно получить текущий индекс параметра @ParameterizedTest.

Например, в следующем тесте:

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

Когда тест выполняется со значением 1, расширение должно получить индекс 1, когда оно работает со значением 3, индексом 2 и и так далее.

Я не нашел простого способа сделать это. В качестве альтернативы я написал два решения:

1 - Использование отображаемого имени:

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 - Использование отражения:

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);
        }
}

В этом репозиторий , я привел примеры с использованием обоих решений.

Есть ли лучший способ добиться этого?

...