'How to test EJB Beans in OpenEJB with JUnit5?

In JUnit 4, I use the following setup to test my EJB beans:

@RunWith(EJBContainerRunner.class)
public class MyEETestWithOneOpenEJB {
    @Inject
    private ACdiBean bean;
 
    @Test
    public void theTest() {
        // do test
    }
}

But in JUnit 5, there is no @RunWith(...) anymore.

Question: How to test with JUnit 5?



Solution 1:[1]

TomEE 8 (since 8.0.7) supports testing with JUnit 5 only (without a transient dependency towards JUnit 4).

The Legacy Way

The legacy EJBContainerRunner was replaced by a related JUnit 5 extension.

If you are using Maven, you would need to add the following dependency to your pom file:

    <dependency>
         <groupId>org.apache.tomee</groupId>
         <artifactId>openejb-junit5-backward</artifactId>
         <version>8.0.9</version>
         <scope>test</scope>
     </dependency>

Subsequently, you can replace

@RunWith(EJBContainerRunner.class)

with

@RunWithEjbContainer

which is a pure JUnit 5 extension. There is no need to add any JUnit 4 dependency into your classpath. A usage example can be found in the module's test source at the TomEE GitHub repository.

The Modern Way

In the same release, the ApplicationComposer was enhanced to support JUnit 5 as an extension. To use it, add

    <dependency>
         <groupId>org.apache.tomee</groupId>
         <artifactId>openejb-junit5</artifactId>
         <version>8.0.9</version>
         <scope>test</scope>
     </dependency>

to your classpath. ApplicationComposer does not require classpath scanning and is faster than the alternative mentioned above.

Just add @RunWithApplicationComposer to your JUnit 5 test class. By default, the container lifecycle is bound to the lifecycle of the test instance. However, other modes are available as well:

  • PER_EACH: A container is started for each test method
  • PER_ALL: A container is started for each test class
  • PER_JVM: A container is started once per JVM
  • AUTO (default): A container is started based on the test instance lifecycle.

An example can be found in the examples section of the TomEE GitHub repository.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1