Thursday, December 1, 2011

JUnit - Partial Mocking of an object under test


So I was trying to write unit tests for my methods using JUnit and EasyMock and the method I was writing unit test for is a method that calls another public method
of the same object under test. In the example below I am writing unit test for methodThatCallsMethodsOneAndTwo(). We don't want to get into the business logic
of other methods, we would just want to concentrate on the method under test.


With EasyMock we can mock some methods of the object under test .

testObject = EasyMock.createMockBuilder(DemoClass.class) .addMockedMethod("methodOne", Integer.class).addMockedMethod("methodTwo",
String.class) .createMock();



See the entire example.

public class DemoClass{

  public String methodOne(Integer demoInputOne){
     //calls some webservice or an ejb or some other object, gets data, processes it and returns a string.
   
     return "abc" ; // this is determined programatically
  }
 
  public List<Integer> methodTwo(String demoInputTwo){
     //Calls some dao, gets the data, does some logic and returns an arraylist
   
     return  demoList; // this is determined programatically
  }
 
  public Boolean methodThatCallsMethodsOneAndTwo(){
    String methodOneResult = methodOne(1);
    List<Integer> methodTwoResult = methodTwo(methodOneResult);
    //does some other logic and returns true or false
    return true;
   }   
}


   public class TestDemoClass{
    DemoClass testObject ;
   
    @Test   
    public void testMethodThatCallsMethodsOneAndTwo() {
        testObject = EasyMock.createMockBuilder(DemoClass.class) .addMockedMethod("methodOne", Integer.class).addMockedMethod("methodTwo",
String.class) .createMock();

   
    Integer demoInputOne = 1 ;   
    List<Integer> demoList = new ArrayList<Integer>();
    demoList.add(1);
    demoList.add(2);
    EasyMock.expect(testObject.methodOne(demoInputOne)) .andReturn("abc");
    EasyMock.expect(testObject.methodTwo("abc")) .andReturn(demoList);
    EasyMock.replay(testObject);
    Assert.assertTrue("This must be true",testObject.methodThatCallsMethodsOneAndTwo());
   
    }
}

Shown below is the old way of doing it in older versions of JUnit. However the methods used are now deprecated in latest versions of JUnit.


testObject = EasyMock.createMock(
DemoClass.class,DemoClass.class.getMethod("nethodOne", new
Class[] {Integer.class}),
DemoClass.class.getMethod("methodTwo",ne
w Class[] {String.class} )) ;


NO WE CAN'T MOCK A PRIVATE METHOD USING EASYMOCK.

No comments:

Post a Comment