1

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 ?

Fabrizio Stellato
  • 1,727
  • 21
  • 52
  • What hibernate version are you using? What is the error you get? In the latest hibernate javadoc (5.4.10.Final) I dont see any `SessionImpl` class. The version wher I can find a `SessionImpl` is here [3.5](https://docs.jboss.org/hibernate/orm/3.5/javadocs/org/hibernate/impl/SessionImpl.html) but not in the package `org.hibernate.internal`. In the latest vesion there is class [SessionDelegatorBaseImpl](https://javadoc.io/static/org.hibernate/hibernate-core/5.4.10.Final/org/hibernate/engine/spi/SessionDelegatorBaseImpl.html) that implements `EntityManager`. Maybe you can try it. – Lini Jan 30 '20 at 22:07
  • 1
    I use a different approach to inject an EntityManager in JUnit 5 by rolling an extension. Not perfect but works. You may have a look on [GitHub](https://github.com/ltmai/javase/tree/master/junit/junit-jpa-extension). – Lini Jan 30 '20 at 22:22

1 Answers1

0

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.

Paulo Araújo
  • 539
  • 3
  • 12