Monday, September 23, 2013

Using Arquillian with JUnit and Glassfish for Integration Testing

We are all familiar with Junit as a unit and integration testing framework. This article talks about configuration of JUnit with Arquillian for Integration testing on Glassfish 4.
Arquillian (http://arquillian.org/) provides a component model for integration tests, which includes dependency injection and container life cycle management. Arquillian lets you ditch the mocks and write real tests. That's because Arquillian brings your test to the runtime, giving you access to container resources, meaningful feedback and insight about how the code really works.

Following article will present a test project, where we have a service endpoint resource class (RESTResource.java) which is a service endpoint for a RESTful webservice. The RESTful request comes to this endpoint class and it calls the business service (ServiceImpl.java). We using Java EE 7, CDI (context & dependency injection - JSR 299 specification) to inject ServiceImpl in RESTResource. Now we use also have a OraServiceDAO that does a resource lookup (using Java EE @Resource) of Oracle Data source. This OraServiceDAO is also injected into ServiceImpl using CDI. This kind of 
The problem most developers will have while writing integration tests would be, how to simulate CDI and JNDI resource look up as done in OraServiceDAO, while doing integration testing without an actual Glassfish 4 environment running. Arquillian come to our rescue and along with JUnit it provides an embedded Glassfish environment for running integration test cases.

First I would like to introduce our project structure. 

RESTResource is the RESTful web service endpoint that receives the GET request.


ServiceImpl is injected into it using CDI. using Arquillian and JUnit we would write an integration test case that would test this business service namely testService API.

ServiceImpl class

If you see, the Oracle DAO OraServiceDAO is injected into this business service class.


OraServiceDAO  class



This class looks up JNDI resource to get the Data source.

Now if you see the complexity of this simple example, framework like JUnit would not be sufficient alone to test CDI and resource look ups done in this example without external help. Arquillian comes to rescue..!!  

Using Arquillian and JUnit we can simulate the Glassfish environment and run test cases.

First I would introduce with the Maven environment setting defined in pom.xml for running Arquillian, JUnit and embedded Glassfish using Maven.

Following versions of dependencies are being used in pom.xml
<properties>
        <arquillian.version>1.0.0.Final</arquillian.version>
        <jersey.version>2.0</jersey.version>
        <junit.version>4.11</junit.version>
        <glassfish.embedded.all.version>4.0</glassfish.embedded.all.version>
        <arquillian.glassfish.embedded.version>1.0.0.CR4</arquillian.glassfish.embedded.version>
   </properties>

I’m using the arquillian-bom (Bill Of Material) who contains all the versions for the arquillian dependencies.


The Arquillian & Junit dependencies:-


Build profile setting:-

Now the resource files defined above and required for Arquillian to correctly setup the resources

arquillian.xml

<?xml version="1.0" encoding="UTF-8"?>
<arquillian xmlns="http://jboss.org/schema/arquillian"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="
        http://jboss.org/schema/arquillian
        http://jboss.org/schema/arquillian/arquillian_1_0.xsd">
    <container qualifier="glassfish-embedded" default="true">
        <configuration>
            <property name="resourcesXml">
              src/test/resources-glassfish-embedded/glassfish-resources.xml
             </property>
        </configuration>
    </container>

</arquillian>

glassfish-resources.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE resources PUBLIC
    "-//GlassFish.org//DTD GlassFish Application Server 3.1 Resource Definitions//EN"
    "http://glassfish.org/dtds/glassfish-resources_1_5.dtd">
<resources>

    <jdbc-resource pool-name="ArquillianEmbeddedOraclePool" jndi-name="jdbc/testresource/ORAlookup"/>
    <jdbc-connection-pool name="ArquillianEmbeddedOraclePool" res-type="javax.sql.DataSource"
        datasource-classname="oracle.jdbc.pool.OracleDataSource" is-isolation-level-guaranteed="false">

  <property name="URL" value="jdbc:oracle:thin:@oraserver.com:1521:ora1"/>
    <property name="User" value="username"/>
    <property name="Password" value="password"/>

    </jdbc-connection-pool>
         

</resources>


Now let us look at the Test class which call its all:-



Line 25 - you have to use @RunWith annotation to specify 
Line 35 - ShrinkWrap api, that assembles it all. Shrinkwrap provides a simple mechanism to assemble archives like JARs, WARs, and EARs with a friendly, fluent API.
Line 47 - Injecting ServiceImpl

This is a JUnit test class that uses Arquillian to create archive that runs on embedded Glassfish env.



The structure of the complete project looks like:-






Finally, you can run maven install or maven test using Eclipse or from command prompt cmd> mvn clean install. You will see in the output logs, that Service and oracle DAO is called.




This example uses Arquillian to startup Glassfish env and run integration testing using JUnit.


Wednesday, September 11, 2013

JAXB - using XmlAdapter class and @XmlJavaTypeAdapter annotation to write custom binding from java bean to xml

We can use JAXB to convert data between a xml and java bean. Using JAXB annotations like @XmlRootElement, @XmlAccessorType & @XmlElement we can achieve marshaling/unmarshaling of java bean to xml and vice versa.

Now sometime we come across problems where we need some custom conversion of an xml attribute to a java object.  When we are binding our own classes to XML, we are hit with a situation where our class representation doesn't match what we'd like to see in the XML.
In those cases, @XmlJavaTypeAdapter comes to our rescue. We can implement a custom java type adapter in the following way.

Identify the conversion from/ to

For example sake, we will be converting a java.lang.String to a custom GUID class (com.myorg.GUID)

Write custom adapter

public class StringToGUIDAdapter extends XmlAdapter<java.lang.String, GUID> {
@Override
public GUID unmarshal(String strGUID) throws Exception {
return new GUID(strGUID);
}
@Override
public String marshal(GUID guid) throws Exception {
if(null == guid)
return null;
else 
return guid.toString();
}
}

As you see, we have to extend XmlAdapter class and implement two of its methods - namely unmarshal & marshal.

Define the annotation in your java bean

Now you need to define your annotation @XmlJavaTypeAdapter on the java field like:-
  
  @XmlJavaTypeAdapter(type=String.class,value =StringToGUIDAdapter.class)
    private GUID                    entity;

And that is it. Your custom binding is ready to be used. 

@XmlJavaTypeAdapter annotation can be used with the following program elements:
  • a JavaBean property
  • field
  • parameter
  • package

This kind of custom binding is very useful when using JAX-RS and JSON.