【问题标题】:Create test instance in Junit 5 with factory method (no dynamic test)使用工厂方法在 Junit 5 中创建测试实例(无动态测试)
【发布时间】:2017-10-08 18:44:02
【问题描述】:

使用 JUnit 4,可以使用运行器来控制测试实例的生命周期。例如,我曾经实现 BlockJUnit4ClassRunner 的方法 createTest() 来微调实例创建(在我的例子中,使用 Weld 来检索 CDI 就绪实例)。

对于 JUnit 5,extensions 应该替换跑步者和规则。然而,我找不到像使用 JUnit 4 那样创建测试实例的方法。

有没有办法告诉 JUnit Jupiter 如何在不使用动态测试的情况下创建我的测试实例(例如,使用 Weld 容器)?

这是我现在在 JUnit 4 中所做的,并且希望能够在 Jupiter 中做的事情:

public class ContainerRunner extends BlockJUnit4ClassRunner {

    private WeldContainer container;

    ...

    @Override
    public Object createTest() {
        return container.select(this.getTestClass().getJavaClass()).get();
    }
}

后来:

@RunWith(ContainerRunner.class)
@Singleton
public class ContainedTest {

    @Inject
    private Logger logger;  // this works

    @Test
    public void testSomething() {
        ...
    }
}

感谢您提供任何见解。

【问题讨论】:

标签: java junit junit5 junit-jupiter


【解决方案1】:

到目前为止,最好使用两个Weld JUnit 5 Extensions 之一。

但要直接回答您的问题,您可以(3 年后)编写一个实现 TestInstanceFactory 的扩展,即:

class ContainerExtension implements TestInstanceFactory {
    private WeldContainer container;

    @Override public Object createTestInstance(TestInstanceFactoryContext factoryContext, ExtensionContext extensionContext) throws TestInstantiationException {
        return container.select(this.getTestClass().getJavaClass()).get();
    }
}

那么您的测试使用@ExtendWith(ContainerExtension.class) 而不是@RunWith(ContainerRunner.class)

【讨论】:

    猜你喜欢
    • 2019-08-19
    • 2017-08-12
    • 2018-12-26
    • 2022-09-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多