Reputation: 59
I need to mock private method and should return true. In ServiceImpl-execute() my request will go to else { } and it will call "eventRequest()". Its a private boolean eventRequest(), So whenever evenRequest() will call i should return true. Can anybody help me out
ServiceImplTest.java
@RunWith(PowerMockRunner.class)
@PrepareForTest({ServiceImpl.class})
public class ServiceImplTest {
@Test
public void testExecute() {
Response response = serviceImpl.execute(request);
Assert.assertNotNull(pushResponse);
Assert.assertEquals(true, pushResponse.isIsSuccess());
}
}
ServiceImpl.java
public class ServiceImpl {
public Response execute(Request request) {
Response response = null;
boolean isSuccess;
if (returnMockResponse(request, notifyRqst)) {
isSuccess = true;
} else {
isSuccess = eventRequest(notifyXmlRqst);
}
response = ResponseBuilder.createResponse(isSuccess);
return response;
}
// Need to mock below private method and should return true.
private boolean eventRequest(String request) throws Exception {
return eventNotifyResponse.isIsSuccess();
}
}
ResponseBuilder.java
public class ResponseBuilder {
public Response createResponse(boolean result) {
Response response = new Response();
response.setIsSuccess(result);
return response;
}
}
Upvotes: 0
Views: 3334
Reputation: 2118
You can create a mock of eventNotifyResponse normally, then use Whitebox to set the private (internal) field.
Assuming your field eventNotifyResponse was of a type named EventNotifyResponse, the test class it would be something like:
EventNotifyResponse evtNotifyResponseMock = mock(EventNotifyResponse.class);
when(evtNotifyResponseMock.isIsSuccess()).thenReturn(true);
Whitebox.setInternalState(serviceImpl, "eventNotifyResponse", evtNotifyResponseMock);
Whitebox is a class of Powermock (org.powermock.reflect.Whitebox).
setInternalState is overloaded. In the example, the parameters used are:
Upvotes: 2
Reputation: 997
Have you try with PowerMock.createPartialMock(ClassWithPrivateMethod.class, "nameOfTheMethodToMock")
and PowerMock.expectPrivate(mockObject, "nameOfTheMethodToMock", argument1, argument2)
as describe in the wiki off powermock ?
https://code.google.com/p/powermock/wiki/MockPrivate
or perhaps see the answer of this question ...
How to mock private method for testing using PowerMock?
Upvotes: 0
Reputation:
Its not possible in jUnit or jMock by default, you can either change the private to public or you can invoke the public method which internally invokes the private method, and make sure that input causes the private method to get called and covered.
Upvotes: 0