Friday, October 14, 2011

Interacting with IBM MQ Series using standalone Java client

In general java developers using JMS will not encounter any issues as we are having JMS libraries in the Application Server along with other J2EE libraries. But interacting with MQ Series from java applications is a tricky thing. This is not visible to developers in many applications. Many of the cases the application interaction with MQ Series is hidden inside a framework/jar file. Below is a simple program to actual interaction with MQ Series. We would be required ibm.mq libraries in the classpath in order to compile and run the program.

MQSender.java
-------------------------------------------------------------------------------
package com.dev.mqtest;

import java.io.IOException;
import java.util.Hashtable;

import com.ibm.mq.MQC;
import com.ibm.mq.MQEnvironment;
import com.ibm.mq.MQException;
import com.ibm.mq.MQMessage;
import com.ibm.mq.MQPutMessageOptions;
import com.ibm.mq.MQQueue;
import com.ibm.mq.MQQueueManager;
public class MQSender {

/**
* @param args
*/
public static void main(String[] args) {

try {
Hashtable properties = new Hashtable();
// MQQueueManager qMgr = new MQQueueManager("MQ Queue Manager Name", properties);

//hostipaddress, port,channel
MQEnvironment.hostname = "11.122.66.45";
MQEnvironment.port=11126;
MQEnvironment.channel = "";

MQQueueManager qMgr = new MQQueueManager("QUEUE_MANAGER_NAME");
            int openOptions =MQC.MQOO_FAIL_IF_QUIESCING + MQC.MQOO_OUTPUT ;

            //Now specify the queue that we wish to open, and the open options...
            MQQueue queue = qMgr.accessQueue("MQ_NAME",openOptions);
            MQMessage mqmsg =new MQMessage();
            mqmsg.characterSet = ((Integer) properties.get("mqcharset")).intValue();
            mqmsg.writeString("This is the message to post....... ");
//            mqmsg.replyToQueueName = "Reply Queue Name";

            //Set the put message options...
            MQPutMessageOptions pmo =new MQPutMessageOptions();

            //put the message on the queue...
            queue.put(mqmsg,pmo);

            //Close the queue...
            queue.close();
            //Disconnect from the queue manager
            qMgr.disconnect();
     

} catch (MQException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

}

}

refer to below link for more details on IBM MQ Series using Java


Thursday, May 19, 2011

Testing Private methods using Reflection

Testing private methods using JUnit is a tricky thing. We have different ways to do so, but I feel using reflection is the better way of doing things. Below is a utility class which invokes the private methods using reflection and return the expected results from the private method.

Calculator.java

package com.dev.junit.test;
public class Calculator {

private int privateField = 0;  
private Integer calculateSimpleInterest(Integer principal, Integer term, Integer rateOfInterest){
        Integer interest = principal*term*rateOfInterest/100;
        return interest;
    }}

PrivateUtility.java 

package com.dev.junit.test;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class PrivateUtility {
   
    public static Object invokePrivate(String methodName, Object object, Class[] signature, Object[] values)
    throws NoSuchMethodException
    {
        Class pvtClass = object.getClass();
        Method method = null;
        while (method == null) {
            try {
                method = pvtClass.getDeclaredMethod( methodName, signature );
            } catch (NoSuchMethodException e) {
                pvtClass = pvtClass.getSuperclass();
                if (pvtClass == null) {
                    throw e;
                }
            }
        }
        method.setAccessible(true);
        try {
            return method.invoke(object, values );
        } catch (IllegalAccessException e) {
            e.printStackTrace();
            throw new NoSuchMethodException( e.toString() );
        } catch (InvocationTargetException e) {
            e.printStackTrace();
            throw new RuntimeException( e.getCause() );
        }
    }
   
    public static void setPrivate(Object object, String fieldName, Object value)
    throws NoSuchFieldException
    {
        try {
            Field field = null;
            Class instanceClass = object.getClass();
            while (field == null) {
                try {
                    field = instanceClass.getDeclaredField( fieldName );
                } catch (NoSuchFieldException e) {
                    instanceClass = instanceClass.getSuperclass();
                    if (instanceClass == null) {
                        throw e;
                    }   }    }
            field.setAccessible(true);
            field.set(object, value);
        } catch (SecurityException e) {
            e.printStackTrace();
            throw new NoSuchFieldException( "Unable to set field [" + fieldName + "]: " + e.toString() );
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
            throw new NoSuchFieldException( "Unable to set field [" + fieldName + "]: " + e.toString() );
        } catch (IllegalAccessException e) {
            e.printStackTrace();
            throw new NoSuchFieldException( "Unable to set field [" + fieldName + "]: " + e.toString() );
        }
    }

   
    public static Integer getPrivate(Object object, String fieldName )
    throws NoSuchFieldException
    {
        try {
            Class instanceClass = object.getClass();
            Field field = null;
            while (field == null) {
                try {
                    field = instanceClass.getDeclaredField( fieldName );
                } catch (NoSuchFieldException e) {
                    instanceClass = instanceClass.getSuperclass();
                    if (instanceClass == null) {
                        throw e;
                    }  }  }
            field.setAccessible(true);
            return (Integer) field.getInt(object);
        } catch (SecurityException e) {
            e.printStackTrace();
            throw new NoSuchFieldException( "Unable to access field [" + fieldName + "]: " + e.toString() );
        } catch (IllegalAccessException e) {
            e.printStackTrace();
            throw new NoSuchFieldException( "Unable to access field [" + fieldName + "]: " + e.toString() );
        }
    }} 
CalculatorPrivateTest.java


package com.dev.junit.test;
import static org.junit.Assert.assertEquals;
import org.junit.Test;
public class CalculatorPrivateTest {

    @Test
    public void testCalculateSimpleInterest(){
        Calculator calc = new Calculator();
        try {
            // invoke private method with object parameters
            Object obj = PrivateUtility.invokePrivate("calculateSimpleInterest", calc, new Class[]{Integer.class,Integer.class,Integer.class}, new Object[]{1000,10,12});
            int i = (Integer)obj;
            assertEquals(1200, i);
          
            // invoke private method with object parameters
            Object obj1 = PrivateUtility.invokePrivate("calculateSimpleInterestPrimitives", calc, new Class[]{Integer.TYPE,Integer.TYPE,Integer.TYPE}, new Object[]{2000,10,12});
            int i1 = (Integer)obj1;
            assertEquals(2400, i1);
          
            //set the value to private fields
            PrivateUtility.setPrivate(calc, "privateField", 200);
          
            //check the value to private fields
            int pvtValue = (Integer)PrivateUtility.getPrivate(calc, "privateField");
            assertEquals(200, pvtValue);
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        }catch (NoSuchFieldException e) {
            e.printStackTrace();
        }
    } }

Friday, April 22, 2011

JUnit Examples

Just JUnit

Calculator.java


package com.dev.junit.test;

public class Calculator {

public int add(int value1, int value2){
return value1+value2;
}
public int substract(int value1, int value2){
return value1-value2;
}
public int multiply(int value1, int value2){
return value1*value2;
}
public int devide(int value1, int value2){
return value1/value2;
}
}

Without Annotations

CalculatorTest.java

package com.dev.junit.test;

import junit.framework.TestCase;

public class CalculatorTest extends TestCase{

Calculator calc = null;
public void setUp(){
// to set up data
// runs before execution of every test case
calc = new Calculator();
}
public void testAdd() {
assertNotNull(calc);
int result = calc.add(4, 2);
assertEquals(6,result);
}
public void testSubstract() {
assertNotNull(calc);
int result = calc.substract(4, 2);
assertEquals(2,result);
}
public void testMultiply() {
assertNotNull(calc);
int result = calc.multiply(4, 2);
assertEquals(8,result);
}
public void testDevide() {
assertNotNull(calc);
int result = calc.devide(4, 2);
assertEquals(2,result);
}
public void tearDown(){
// to remove data
// runs after execution of every test case
}
}

With Annotations

CalculatorTest.java

package com.dev.junit.test;

import static org.junit.Assert.*;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

public class CalculatorTest {

Calculator calc = null;
@Before
public void setUp() throws Exception {
// to setup data
// runs before execution of every test case
calc = new Calculator();
}

@After
public void tearDown() throws Exception {
// to remove data
// runs after execution of every test case
}

@Test
public void testAdd() {
assertNotNull(calc);
int result = calc.add(4, 2);
assertEquals(6,result);
}

@Test
public void testSubstract() {
assertNotNull(calc);
int result = calc.substract(4, 2);
assertEquals(2,result);
}

@Test
public void testMultiply() {
assertNotNull(calc);
int result = calc.multiply(4, 2);
assertEquals(8,result);
}
@Test
public void testDevide() {
assertNotNull(calc);
int result = calc.devide(4, 2);
assertEquals(2,result);
}
}

Thursday, April 21, 2011

Unit Testing Frameworks

JUnit framework helps us to write and execute unit testing programs to test Java applications. We write a test case for each business method, and business logic. Sometimes we write many test cases for testing a single business method depending on the permutations and combinations to check that business logic. We also write test cases for constructors when business logic present in Constructor of a Class. We also write test cases for private methods when they have business logic. The Thumb Rule of unit test cases is: We write test case for testing business logic, where ever it present.

Unit testing applications helps us to:
Ø  To provide high-quality software.
Ø  Improve the developer’s confidence and customer’s satisfaction.
Ø  Test very big applications and business logic in a single click.
Ø  Make sure that the applications to perform consistently in the same way.
Ø  Provide a proof of the application unit testing and metrics.

Junit is sufficient for writing Unit testing applications in Java. But for writing Unit testing applications in J2EE environment we have few other frameworks. We have very good frameworks in Java/J2EE for writing Junit test cases.

Below are few frameworks. These are the extensions to the JUnit framework.

v  Cactus :
For testing server side programs like Servlet, EJB etc., The tests are executed in the Container. Hence the tests executed while server running.

v  JMock:
This framework supports TDD(Test-Driven-Development) for writing java code with mock objects.

v  Shale:
Shale framework provides mock objects for testing server-side java components in absence of container. Shale provides mock object libraries and base classes for creating Junit test cases. This focused on making easy to write test cases for Servlet. JSF, ViewControllers.

v  EasyMock:
This is a mock framework which provides mock objects to create Junit test cases for given interfaces. This provides an easy way to use mock objects. Easy mock provides mock objects for any given interfaces.

This is a light weight framework for writing Unit testing applications in J2EE environment. It supports servlet, filters, jstl, EJB,JMS, JCA, JDBC.

v  DBUnit :
This is a mock framework which provides mock objects to test Database programs. This provides mock objects for Connection, Statement, ResultSet etc.