How can I unit test the ProcessorBean? Since I only wan\'t to test the ProcessorBean and not the Dao, I need to stub or mock the Dao, but I have no idea how I could do that
There's some support in OpenEJB you might find useful in combination with mocking.
As an alternative to the EJB 3.0 Embedded EJBContainer API, you can simply build your app up 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 a testcase run by the ApplicationComposer
. It is a simple wrapper for a JUnit test runner that looks for @Module
methods which can be used to define your app.
This is actually how OpenEJB has done all its internal testing for years and something we decided to open up in the last few releases (since 3.1.3). It's beyond powerful and extremely fast as it cuts out classpath scanning and some of the heavier parts of deployment.
The maven dependencies might look like so:
<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>
If you want to mock any object or create its stub, you can use additional library, e.g. Mockito. It allows you very easily mock any class or even an interface.
Additional reading: