📝

JUnit5 引数の値の取得方法

2022/11/22に公開

@link https://github.com/junit-team/junit5/issues/1139

自前でExtention Interface をオーバーライドして作成する際など

class TestExtension
        implements BeforeEachCallback
{
    @Override
    public void beforeEach(ExtensionContext extensionContext)
    {
        Parameter[] parameters = extensionContext.getTestMethod().get().getParameters();
        Object[] argObjects = getArgumentValues(extensionContext);
        for (int i = 0; i < parameters.length; i++)
        {
            System.out.println(parameters[i].getName() + " : " + argObjects[i]);
        }
    }

    private Object[] getArgumentValues(ExtensionContext extensionContext)
    {
        try
        {
            Method method = ReflectionUtils.findMethod(extensionContext.getClass(), "getTestDescriptor").orElse(null);
            TestMethodTestDescriptor descriptor =
                    (TestMethodTestDescriptor)ReflectionUtils.invokeMethod(method, extensionContext);

            //Get the TestTemplateInvocationContext
            Field templateField = descriptor.getClass().getDeclaredField("invocationContext");
            templateField.setAccessible(true);
            TestTemplateInvocationContext template = (TestTemplateInvocationContext)templateField.get(descriptor);

            //Get the params finally
            Field argumentsField = template.getClass().getDeclaredField("arguments");
            argumentsField.setAccessible(true);
            Object[] params = (Object[])argumentsField.get(template);

            return params;

        }
        catch (Exception e)
        {
            return new Object[0];
        }
    }
}

Discussion