如何将不同的变量传递给 JUnit5 中的 beforeEach 挂钩

How to pass in a different variable to the beforeEach hook in JUnit5

我的测试用例设置相当冗长,位于 @beforeEach 挂钩中。

问题是 @beforeEach 挂钩中的第一个方法需要根据测试 运行 使用不同的变量,否则我将不得不复制整个测试 Class 来适应变量的变化,这当然是不理想的。

我当前的设置是:

@beforeEach
@afterEach

@Test
@Test
@Test

Essentially, all 3 tests requires a different variable to be injected into the beforeEach hook.

根据我的阅读,ParameterResolver 可以工作,但我得到的似乎会引发异常,因为我在 class 的其他地方使用了 @Test 注释(我需要的):

public class ValidListParameterResolver implements ParameterResolver {

    private static List<String> LIST_OF_STRINGS_TO_USE = ImmutableList.of("a", "b");

    @Override
    public boolean supportsParameter(ParameterContext parameterContext, ExtensionContext extensionContext) throws ParameterResolutionException {
        return true;
    }

    @Override
    public Object resolveParameter(ParameterContext parameterContext, ExtensionContext extensionContext) throws ParameterResolutionException {
        return LIST_OF_STRINGS_TO_USE.get(new Random().nextInt(LIST_OF_STRINGS_TO_USE.size()));
    }
}

然后在我的测试中Class:

@BeforeEach
@ExtendWith(ValidListParameterResolver.class)
    void create(String file) throws IOException {

        Type name = method(file);
}

有没有人实现过这个?

非常感谢您的帮助。

这里有一些提示可以帮助您走上正确的道路。

supportsParameter() 应该 never return true 作为硬编码值。相反,ParameterResolver 必须确定它是否应该解析参数——例如,按类型或注释。

无法在 @BeforeEach 方法(或任何其他生命周期方法)上注册扩展。您将需要在 class 测试中用 @ExtendWith.

注册它

如果您想知道@BeforeEach方法中将要执行哪个测试方法,请将TestInfo testInfo参数添加到@BeforeEach方法的参数列表中。然后,您可以在 TestInfo.

中访问测试 Method