Reputation: 57
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
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.
pruivate method1()
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