user2181531
user2181531

Reputation: 57

How to access the object inside the private method?

I have mocked the private method using the PowerMock/Mockito , now my question here is how can I access the object declared inside this method ?

for example .

private void method1()
{
MyObject ob = new MyObject();

}

now in my test code I want to access the ob object to verify the values .

Upvotes: 2

Views: 1798

Answers (1)

ppeterka
ppeterka

Reputation: 20726

This guide details mocking a constructor call using PowerMock:

... But with PowerMock you don't have to change the code, instead you can instruct PowerMock to intercept the call to new File(..) and return a mock object instead. To do this we start by creating a mock of type File.class as usual:

File fileMock = createMock(File.class);

To expect the call to new File we simply do:

expectNew(File.class, "directoryPath").andReturn(fileMock);

So in your case, you should have these in your test case or setup method:

MyObject mockOb = createMock(MyObject.class);
expectNew(MyObject.class).andReturn(mockOb);

By adding these, you will have the following behaviour:

Whenever there is a new MyObject() in your code run by the test case, the object instance mocked by PowerMock will be returned. So it does not matter where in your code you create a new MyObject instance, it will be the very same one created by the createMock() function.

EDIT

lets take example

Class A { 
 private void method1() 
 { 
   Obj obj = new Obj(); 
    obj.setX(10);
 } 
 //Here I want to access the obj object to verify the values 
}

To accomplish this, you have to think a bit differently.

  1. create real A instance
  2. set up mocking for the Obj constructor
  3. run your logic that triggers the pruivate method1()
  4. check the values on the mocked Obj instance
    • if the values are not testable (something modifies it in the logic), zou could check if the setX() was called the appropriate times.

Something along these lines:

@Test
public void testMyPrivateMethod() {
    //1. object with the logic to test
    A a = new A();

    //2. set up mocking
    Obj mockObj = createMock(Obj.class);
    expectNew(Obj.class).andReturn(mockObj);

    //3. trigger logic to test
    a.someOtherMethodThatCallsMethod1();

    //4. test Obj (find out if setX() has been called or not)
    verify(mockObj).setX(any(Integer.class));
}

Upvotes: 2

Related Questions