Roee Gavirel
Roee Gavirel

Reputation: 19445

How to Mock private method which is called from the constructor using PowerMockito

Example of the problem:

class ToBeTested {
    private MyResource myResource;
    public toBeTested() {
        this.myResource = getResource();
    }

    private MyResource getResource() {
        //Creating My Resource using information form a DB
        return new MyResource(...);
    }
}

I would like to mock the getResource() so I would be able to provide a mock instance of MyResource. All the examples I found on how to mock a private method are based on first creating the ToBeTested instance and then replace the function but since it's being called from the constructor in my case it's to late.

Is it possible to mock the private function to all instances in advance of creating them?

Upvotes: 4

Views: 2629

Answers (1)

kuhajeyan
kuhajeyan

Reputation: 11017

Not directly but, you can suppress and then simulate with power mockito

    @RunWith(PowerMockRunner.class)
    @PrepareForTest(ToBeTested .class)
    public class TestToBeTested{

    @before
    public void setup(){
      suppress(method(ToBeTested.class, "getResource"));
    }

    @Test
    public void testMethod(){
        doAnswer(new Answer<Void>() {
      @Override
      public MyResource answer(InvocationOnMock invocation) throws Throwable {
           return new MyResource();
      }
 }).when(ToBeTested.class, "getResource");
    }

       ToBeTested mock = mock(ToBeTested.class);
       mock.myMethod();
       //assert
    }

Upvotes: 1

Related Questions