Unit-testing a ejb3.0 into which another ejb is injected

How can I unit test ProcessorBean? Since I just did not test ProcessorBean, not Dao, I need to stifle or mock Dao, but I don’t know how to do this with Junit.

I am using Junit4 and Ejb3.0

@Stateless public class ProcessorBean { @EJB private Dao dao; public void process() { //logic to be tested } } 
+5
source share
2 answers

There is support in OpenEJB that you may find useful in combination with ridicule.

As an alternative to the EJB 3.0 Embedded EJBContainer API, you can simply create your application in code.

 import junit.framework.TestCase; import org.apache.openejb.jee.EjbJar; import org.apache.openejb.jee.StatelessBean; import org.apache.openejb.junit.ApplicationComposer; import org.apache.openejb.junit.Module; import org.junit.Test; import org.junit.runner.RunWith; import javax.ejb.EJB; @RunWith(ApplicationComposer.class) public class ProcessorBeanTest extends TestCase { @EJB private ProcessorBean processorBean; @Module public EjbJar beans() { EjbJar ejbJar = new EjbJar(); ejbJar.addEnterpriseBean(new StatelessBean(ProcessorBean.class)); ejbJar.addEnterpriseBean(new StatelessBean(MockDao.class)); return ejbJar; } @Test public void test() throws Exception { // use your processorBean } } 

Here we see the test string executed by ApplicationComposer . This is a simple JUnit test runner shell that looks for @Module methods that can be used to define your application.

This is actually how OpenEJB conducted all of its internal audits over the years and something that we decided to open in the last few releases (starting with 3.1.3). It cannot be powerful and extremely fast because it cuts off class scans and some of the heavier parts of the deployment.

The maven dependencies might look like this:

  <dependencies> <dependency> <groupId>org.apache.openejb</groupId> <artifactId>javaee-api</artifactId> <version>6.0-3-SNAPSHOT</version> <scope>provided</scope> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.8.1</version> <scope>test</scope> </dependency> <!-- The <scope>test</scope> guarantees that none of your runtime code is dependent on any OpenEJB classes. --> <dependency> <groupId>org.apache.openejb</groupId> <artifactId>openejb-core</artifactId> <version>4.0.0-beta-1</version> <scope>test</scope> </dependency> </dependencies> 
+3
source

If you want to make fun of any object or create its stub, you can use an additional library, for example. Mockito . This allows you to easily make fun of any class or even interface.

Additional Information:

+1
source

Source: https://habr.com/ru/post/905559/


All Articles