Aliaksei
Aliaksei

Reputation: 1457

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?

Upvotes: 2

Views: 1171

Answers (2)

rzo1
rzo1

Reputation: 5751

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.

Upvotes: 1

Kotse
Kotse

Reputation: 418

You will need to write your own EJBContainerExtension to replace the Runner or find an already existing one. The latter is unfortunately not very likely at this moment, JUnit5 is still not in GA and there are not many official extensions yet.

If you want to, read about JUnit 5 extension model here

Upvotes: 1

Related Questions