how to partial mock public method using PowerMock?

maverick picture maverick · May 25, 2012 · Viewed 12.4k times · Source

Following is my class

public class SomeClass {
    public ReturnType1 testThisMethod(Type1 param1, Type2 param2) {
        //some code
        helperMethodPublic(param1,param2);
        //more code follows  
    }   

    public ReturnType2 helperMethodPublic(Type1 param1, Type2 param2) {
        //some code            
    }
} 

So in the above class while testing testThisMethod(), I want to partially mock helperMethodPublic().

As of now, I am doing the following:

SomeClass someClassMock = 
    PowerMock.createPartialMock(SomeClass.class,"helperMethodPublic");
PowerMock.expectPrivate(someClassMock, "helperMethodPublic, param1, param2).
    andReturn(returnObject);

The compiler doesn't complain. So I try to run my test and when the code hits the helperMethodPublic() method, the control goes into the method and starts to execute each line of code in there. How do I prevent this from happening?

Answer

pedorro picture pedorro · May 25, 2012

Another solution that doesn't rely on a mock framework would be to override 'helperMethodPublic' in an anonymous subclass defined within your test:

SomeClass sc = new SomeClass() {
   @Override
   public ReturnType2 helperMethodPublic(Type1 p1, Type2 p2) {
      return returnObject;
   }
};

Then when you use this instance in your test it will run the original version of 'testThisMethod' and the overridden version of 'helperMethodPublic'