how to partial mock public method using PowerMock?

12.9k views Asked by At

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?

3

There are 3 answers

2
pedorro On

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'

0
jeff On

I would guess this is because your "helperMethodPublic" is not a private method (as in PowerMock.expectPrivate). PowerMock is a framework that extends other mocking frameworks to add things such as mocking private and static methods (which JMock, Mockito, etc don't handle). Doing a partial mock of public methods should be something your underlying mock framework handles.

0
psb On

I think it is because of what Jeff said.

Try this - setting up an expectation just as any other mocked method:

SomeClass someClassMock = PowerMock.createPartialMock(SomeClass.class,
                                                      "helperMethodPublic");

EasyMock.expect(someClassMock.helperMethodPublic(param1, param2)).
    andReturn(returnObject);

PowerMock.replayAll();