Tuesday, March 15, 2011

Java Unit testing

 

Java Unit Testing:

 

1.    Tool: JUnit.

2.    Process:

a.    Sources has the new folder structure added for this NGRP->UnitTesting.

b.    Use Eclipse to generate the unit test skeleton for your target class [All the screenshots are self explanative] ->>>> Look at the folder structure in clearcase

Naming Convention: <TargetClass>Test

Choose target method to test choose checkboxes as below

Note: Never add the cases to clearcase before testing locally. If eclipse plugin claims just cancel the dialog.

 

c.     Most of the cases it is not as straight forward to write unit test , sometimes methods calls other methods in different layer.

To unit test such methods we should start doing Refactoring.

Target Class:

class TestActionClass {

...

  public subscriptionTO callRules(subscriptionTO) {

    if (level=”G”){

subscriptionTO.level=”G”;

}

elseif(level=”A”){

subscriptionTO.level=”A”;

}

    RemoteService r = new RemoteService();

    r.callRules(subscriptionTO);

return subscriptionTO;

}

..

}

With the above example you cannot unit test as the function call will try to call RemoteService which needs server to be running and ofcourse application to be deployed.

 

Action-> Refactor the call to Remote method to make this method[callRemote] unit testable:

 

Refactored Class:

class TestActionClass {

...

  public subscriptionTO callRules(subscriptionTO) {

    if (level=”G”){

subscriptionTO.level=”G”;

}

elseif(level=”A”){

subscriptionTO.level=”A”;

}

    RemoteService r = createRemoteService();

    r.callRules(subscriptionTO);

return subscriptionTO;

}

..

protected RemoteService createRemoteService(){

return new RemoteService();

}

 

}

 

Now you can write a unit Testcase as follows:

Unit Test Class:

class TestActionClassTest {

MYObject sampleObject = new MYObject();

...

     @Before

public void setUp() throws Exception {

      sampleObject.level=”G”;       

}

 

@Test

public void testCallRules() {

        TestActionClass t = TestActionClass(){

        protected RemoteService createRemoteService(){

            return sampleObject;

             }

        };

}

..

}

 

As you can see above now I have overridden the createRemoteService method in my unit testcase, thus passing my mock object to test callRemote and avoid calling other layers.

 

Reference: http://www.ibm.com/developerworks/library/j-mocktest.html

 

Technical Debt