Friday, June 1, 2007

JMock and how to use.

Today i use JMock for my projects. I should say that it is a good tool for testing.
But finding how to use it makes me crazy. But now i have just resolved all my problems.
It related to the jax-ws mock object. JAX-WS uses the abstract instead of the interface so
it makes using jmock is difficult task. But thanks for new lib JMock 2.x, it support abstract class also concrete class. Following is sample of using jmock for jax-ws soap handler for the unit test purpose.

Step to use:
Using the latest lib JMock 2.x lib

Import org.jmock.Expectations;
import org.jmock.integration.junit3.MockObjectTestCase;
import org.jmock.lib.legacy.ClassImposteriser;

protected final void setUp() throws Exception {
super.setUp();
setImposteriser(ClassImposteriser.INSTANCE);
soapHandlerImpl = new SoapHandlerImpl();
}

public final void testHandleMessage(){
//create mock object
final SOAPMessageContext smc = mock(SOAPMessageContext.class);
final SOAPHeader mockSoapHeader = mock(SOAPHeader.class);
final SOAPMessage mockSoapMessage1 = mock(SOAPMessage.class);
final SOAPMessage mockSoapMessage2 = mock(SOAPMessage.class);
final SOAPHeaderElement mockSoapHeaderElement =
mock(SOAPHeaderElement.class);
final SOAPHeaderElement soapSessionIDHashTag =
mock(SOAPHeaderElement.class);
final SOAPHeaderElement soapFromTag = mock(SOAPHeaderElement.class);
final SOAPHeaderElement soapFromTo = mock(SOAPHeaderElement.class);

//Make the expectation. Please remember that the expectation have to be
//correct or the exception occur. The exception message is not useful to resolve
checking(new Expectations() {
{
one(smc).get(MessageContext.MESSAGE_OUTBOUND_PROPERTY);
will(returnValue(true));
}
}); //simulate function getmessage for soapmessage.

//call function to test with mock parameter.
soapHandlerImpl.handleMessage(smc) ;
}
Some note:
To make the test run with out exception, we have to define how many mock object you need in the function. You should also count the number of function of mock object which will be called and the data for each calls. All of them have to be explicit define or you will got an exception in unit test.
I wrote this to remind me the problems when i do my project in company. I met a lot of prolems with that.

No comments:

Google