Arquillian TestNG: @Before Annotations and CDI

829 Views Asked by At

I am using Arquillian and TestNG with CDI.

Before each test I need access to some members that are CDI beans to do some setup before each test. But i noticed that in every @Before annotation the CDI beans were not injected, but in the @Test annotated method they are.

Can someone explain me why:

1) CDI beans are not yet injected in the @BeforeXXX annotated methods part of the test life cyle?
2) How can I do some setup and access CDI beans before the Tests?
3) Would be correct used the "dependency" attribute in the @Test annotation?

Thank you so much.

1

There are 1 best solutions below

0
On

I think I already understood the problem.

The tests run in two different places: - in the client: maven jvm - in the container: server jvm

In the client side, the CDI beans are not available in the @BeforeMethod, but they will when the test is running in the container. Basically if we need to access CDI beans in the before method we just need to make sure that the test is running in the container. To accomplish this i created a class that extends Arquillian and expose a method that does this.

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

}

We just have to do this check in @BeforeMethod method

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

In the end, the tests in the client looks like they are ignored to reflect the results of the tests that were executed in the container.

If this is wrong, can someone please correct?

Thank you all anyway. I Hope this help