Retrieve Alternative entityManager on unit test though CDI

462 Views Asked by At

I'm using Junit 5, Java bath that run under a webapp EE8 environment.

On the web app, I actually have a resources class that is employed as a producer:

@ApplicationScoped
public class Resources {

    @Produces
    public Logger produceLog(InjectionPoint injectionPoint) {
        return LoggerFactory.getLogger(injectionPoint.getMember().getDeclaringClass().getName());
    }

    @Produces
    @PersistenceContext(unitName = "primary")
    private EntityManager entityManager;

}

Now I want to write some SE test, and I need to retrieve an alternative entity manager, something like:

public class MockResources {

    @Alternative
    @JobScoped
    @Produces
    public EntityManager getEntityManager() {
        return Persistence.createEntityManagerFactory("primary").createEntityManager();
    }

}

The issue is that I don't know how to retrieve this alternative entity , as beans.xml want a class (I tried with Hibernate SessionImpl but it doesn't work), neither @Stereotype looks good for my case.

<beans xmlns="http://xmlns.jcp.org/xml/ns/javaee"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/beans_1_1.xsd"
       bean-discovery-mode="all">
    <alternatives>
        <class>org.hibernate.internal.SessionImpl</class>
    </alternatives>
</beans>

Any help ?

1

There are 1 best solutions below

0
Paulo Araújo On

You should create an entire @Alternative Resources producer bean, as in

@Alternative
@ApplicationScoped
public class TestResources {
    @Produces
    public Logger produceLog(InjectionPoint injectionPoint) {
        return LoggerFactory.getLogger(injectionPoint.getMember().getDeclaringClass().getName());
    }

    @Produces
    private EntityManager getEntityManager() {
        // create your new entitymanager here
        return Persistence.createEntityManagerFactory("testunitname").createEntityManager();
    }
}

Then define your test alternative class on test beans.xml as described on your question.