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;
}
}
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:
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments