10 - Using JUnit in a java project: Page 2 of 3

10.2 JUnit – testing Ejbs

J2EE technology has become the most popular platform for multi-tiered applications based on components – JSP and servlets - and Enterprise JavaBeans – EJB components.

There are two options to test EJB components with JUnit tests:

  1. The test run within the container --- this means that the tests should be deployed to the container.
  2. The tests run in different JVMs and act as a client against a remote EJB container.

EJB components are required to be unit tested independently. Every component tested in isolation helps to decrease the number of bugs and increase the quality of the software.

Unit testing EJB components should be easy and should not consume time and effort. It should exercise some precise method in a specific context.

We can choose the first option to test an EJB component with JUnit within a container. As an example we can create a Maven project (see examples in the previous chapters).

In order to emulate the container we need a dependency to be added to pom.xml:

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.somecompany.app</groupId>
  <artifactId>EJBJUnitTestSample</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <name>EJB Test with JUnit</name>
  <dependencies>
        <dependency>
            <groupId>javax</groupId>
            <artifactId>javaee-api</artifactId>
            <version>7.0</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
          <groupId>junit</groupId>
          <artifactId>junit</artifactId>
          <version>4.8.1</version>
          <scope>test</scope>
          <type>jar</type>
        </dependency>
        <dependency>
          <groupId>org.glassfish.main.extras</groupId>
          <artifactId>glassfish-embedded-all</artifactId>
         <version>3.1.2</version>
         <scope>compile</scope>
       </dependency>
  </dependencies>
</project> 

The dependency has the coordinates: org.glassfish.main.extras: glassfish-embedded-all:3.1.2:compile we can find it at Maven central repository http://mvnrepository.com/artifact/org.glassfish.main.extras.We have to create the bean and the test class :

import javax.ejb.Stateless;

/**
 * Session Bean implementation class CalculatorBean
 */

@Stateless
public class CalculatorBean {   
    public int addTwoNumbers(int first, int second) {
        return first + second;
    }    
}

import static org.junit.Assert.*;

import javax.ejb.embeddable.EJBContainer;
import javax.naming.Context;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

/**
 * test class implementation
 */

public class MyCalculatorTest {

    private Context  ctx;
    private EJBContainer ejbContainer;

    @Before
    public void setUp() {
        ejbContainer = EJBContainer.createEJBContainer();
        System.out.println("Opening the container" );
        ctx = ejbContainer.getContext();
    }

    @After
    public  void tearDown() {
        ejbContainer.close();
        System.out.println("Closing the container" );
    }

    @Test
    public void testSimpleAddition() throws Exception {

        CalculatorBean  calculatorBean = 
                       (CalculatorBean)ctx.lookup("java:global/classes/CalculatorBean");
        assertNotNull( calculatorBean);
        int result = (int) calculatorBean.addTwoNumbers(2, 2);
        assertTrue("2+2=4", result == 4);
    }    
}

In setup() method the container will be created and the context will look for the CalculatorBean class (already compiled).

The new created object calculatorBean will be tested if it is not null and then the method addTwoNumbers will be tested.

We can launch the JUnit test from the Run Configuration option or simply click right on the test class and choose Run as JUnit test.

In the console we will get the trace with the container creation and then the test result:

………

 [INFO] Scanning for projects...

[INFO]

…..

 [INFO] ------------------------------------------------------------------------

[INFO] Building EJB Test with JUnit 0.0.1-SNAPSHOT

[INFO] ------------------------------------------------------------------------

[INFO]

[INFO] --- maven-clean-plugin:2.5:clean (default-clean) @ EJBJUnitTestSample ---

[INFO] Deleting C:\Users\vtg9234\workspace\EJBJUnitTestSample\target

[INFO]

………

[INFO] --- maven-compiler-plugin:2.5.1:compile (default-compile) @ EJBJUnitTestSample ---

….

[INFO] Compiling 1 source file to C:\Users\vtg9234\workspace\EJBJUnitTestSample\target\classes

[INFO]

……

[INFO] Copying 0 resource

[INFO]

[INFO] --- maven-compiler-plugin:2.5.1:testCompile (default-testCompile) @ EJBJUnitTestSample ---

[ [INFO] Compiling 1 source file to C:\Users\vtg9234\workspace\EJBJUnitTestSample\target\test-classes

[INFO]

[INFO] --- maven-surefire-plugin:2.12.4:test (default-test) @ EJBJUnitTestSample ---

[INFO] Surefire report directory: C:\Users\vtg9234\workspace\EJBJUnitTestSample\target\surefire-reports

-------------------------------------------------------

 T E S T S

-------------------------------------------------------

Running MyCalculatorTest

Feb 01, 2015 2:52:47 PM org.glassfish.ejb.embedded.EJBContainerProviderImpl getValidFile

……..

Feb 01, 2015 2:52:48 PM com.sun.enterprise.v3.server.AppServerStartup run

INFO: GlassFish Server Open Source Edition 3.1.2 (java_re-private) startup time : Embedded (414ms), startup services(457ms), total(871ms)

Feb 01, 2015 2:52:48 PM

………

Feb 01, 2015 2:52:59 PM com.sun.enterprise.security.SecurityLifecycle onInitialization

INFO: SEC1010: Entering Security Startup Service

…………………

 

Feb 01, 2015 2:52:59 PM com.sun.enterprise.security.SecurityLifecycle onInitialization

INFO: SEC1011: Security Service(s) Started Successfully

………………….

Feb 01, 2015 2:53:01 PM com.sun.ejb.containers.BaseContainer initializeHome

INFO: EJB5181:Portable JNDI names for EJB CalculatorBean: [java:global/classes/CalculatorBean!CalculatorBean, java:global/classes/CalculatorBean]

Feb 01, 2015 2:53:01 PM org.glassfish.deployment.admin.DeployCommand execute

INFO: classes was successfully deployed in 11.599 milliseconds.

Opening the container

PlainTextActionReporterSUCCESSNo monitoring data to report.

Feb 01, 2015 2:53:03 PM org.glassfish.admin.mbeanserver.JMXStartupService shutdown

INFO: JMX001: JMXStartupService and JMXConnectors have been shut down.

Feb 01, 2015 2:53:03 PM com.sun.enterprise.v3.server.AppServerStartup stop

INFO: Shutdown procedure finished

Feb 01, 2015 2:53:03 PM AppServerStartup run

INFO: [Thread[GlassFish Kernel Main Thread,5,main]] exiting

Closing the container

Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 16.425 sec

 

Results :

Tests run: 1, Failures: 0, Errors: 0, Skipped: 0

[INFO]

[INFO] --- maven-jar-plugin:2.4:jar (default-jar) @ EJBJUnitTestSample ---

[INFO] Building jar:

----

[INFO] ------------------------------------------------------------------------

[INFO] BUILD SUCCESS

[INFO] ------------------------------------------------------------------------

[INFO] Total time: 18.733 s

[INFO] Finished at: 2015-02-01T14:53:04+02:00

[INFO] Final Memory: 18M/44M

[INFO] ------------------------------------------------------------------------

If we launch test with the second option we can see the result in Eclipse JUnit console:

Like us on Facebook