How to partially mock a public method using PowerMock?

Below 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 when testing testThisMethod () I want to partially mock helperMethodPublic ().

I am currently doing the following:

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

The compiler does not complain. So I try to run my test, and when the code gets into the helperMethodPublic () method, the control goes into the method and starts to execute each line of code. How to prevent this?

+3
source share
3 answers

Another solution that does not rely on the layout structure would be to override "helperMethodPublic" in the anonymous subclass defined in your test:

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

, , "testThisMethod" "helperMethodPublic"

+8

, - , .

- , :

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

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

PowerMock.replayAll();
+4

, , "helperMethodPublic" ( PowerMock.expectPrivate). PowerMock - , , , ( JMock, Mockito .. ). -, .

+1

All Articles