java - Arquillian 测试NG : @Before Annotations and CDI

标签 java testng jboss-arquillian

我正在将 Arquillian 和 TestNG 与 CDI 结合使用。

在每次测试之前,我需要访问一些作为 CDI bean 的成员,以便在每次测试之前进行一些设置。但我注意到,在每个 @Before 注释中,CDI bean 都没有注入(inject),但在 @Test 注释方法中它们是注入(inject)的。

有人可以解释一下为什么吗:

1) CDI bean 尚未注入(inject)到测试生命周期的 @BeforeXXX 带注释的方法部分中?
2) 在测试之前如何进行一些设置并访问 CDI bean?
3)在@Test注释中使用“dependency”属性是否正确?

非常感谢。

最佳答案

我想我已经理解了这个问题。

测试在两个不同的地方运行: - 在客户端:maven jvm - 在容器中:服务器jvm

在客户端,CDI bean 在 @BeforeMethod 中不可用,但当测试在容器中运行时它们将可用。基本上,如果我们需要在 before 方法中访问 CDI bean,我们只需要确保测试正在容器中运行。为了实现这一点,我创建了一个扩展 Arquillian 的类并公开了一个执行此操作的方法。

    public abstract class BaseArquillianTest extends Arquillian {
    @ArquillianResource
    protected InitialContext initialContext;

    @Deployment
    @OverProtocol("Servlet 3.0")
    public static WebArchive createDeployment() {
        WebArchive war = PackagingUtil.getWebArchiveForEJB();
        return war;
    }

    protected boolean inContainer() {
       // If the injection is done we're running in the container.
       return (null != initialContext);
    }

}

我们只需在 @BeforeMethod 方法中进行此检查

@BeforeMethod(alwaysRun = true)
public void beforeMethod() throws Exception {
    System.out.println("********* Initing beforeMethod");
    if(inContainer()) {
        System.out.println("$$$$$$ I am in a container");
        Assert.assertNotNull(allRiskConfigurations);

    } else {
        System.out.println("$$$$$$ I am NOT in a container");
    }
}

最后,客户端中的测试看起来像是被忽略了,以反射(reflect)在容器中执行的测试的结果。

如果这是错误的,请有人纠正吗?

无论如何,谢谢大家。我希望这有帮助

关于java - Arquillian 测试NG : @Before Annotations and CDI,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26855306/

相关文章:

java - Arquillian Cube 基本示例/教程 JMX 远程访问超时

testng - io.cucumber.junit.CucumberOptions vs io.cucumber.testng.CucumberOptions vs cucumber.api.CucumberOptions 我应该选择哪一个

java - TestNG - 从不同的类导入/运行测试

java - 删除 swt 对话框中的默认对话框区域

java - java中按字母顺序对输出文件进行排序

java - 阿基利安 : Transaction is required to perform this operation

maven - Arquillian 收缩包装

testing - Arquillian 与 Mockito 和 CDI

java - 错误 : No resource identifier found for attribute `requestLegacyExternalStorage` and `preserveLegacyExternalStorage` in package `android`

java - 从静态 block 或方法初始化静态最终 int 并在注释中使用它