Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to partial mock public method using PowerMock?

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?

like image 205
maverick Avatar asked May 25 '12 16:05

maverick


1 Answers

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'

like image 65
pedorro Avatar answered Nov 07 '22 13:11

pedorro