Powermock for bullying instance methods called by other execution methods

In this code, I mocked one of the methods of the ValidateHandlerSoapClient class that was created and called this method (soapClientSpy.processSoapRequestRespons) in validateMsisdnHandlerIRSpy.validate (). So soapClientSpy.processSoapRequestResponse does not work, the real method is called instead.

@RunWith(PowerMockRunner.class) @PrepareForTest({ValidateMsisdnHandler.class,ValidateHandlerSoapClient.class}) public class Demo { MessageControl messageControl=PowerMockito.mock(MessageControl.class); Validate validate=PowerMockito.mock(Validate.class); ValidateMsisdnHandlerIR validateMsisdnHandlerIRSpy = PowerMockito.spy(new ValidateMsisdnHandlerIR()); ValidateHandlerSoapClient soapClientSpy = PowerMockito.spy( new ValidateHandlerSoapClient()); @Before public void initialize() throws Exception { PowerMockito.when(validate.getAccountId()).thenReturn("0879221485"); PowerMockito.doReturn(true).when(validateMsisdnHandlerIRSpy, "isPrePaid",anyString()); MemberModifier.field( ValidateMsisdnHandlerIR.class, "endDate").set( validateMsisdnHandlerIRSpy, "10-FEB-2015"); PowerMockito.when(soapClientSpy.processSoapRequestResponse(anyString())).thenReturn(true); PowerMockito.whenNew(ValidateHandlerSoapClient.class).withNoArguments().thenReturn(soapClientSpy); } @Test public void testValidateMsisdn_Cr6_Roverprempay_Not_Roverpayg() throws Exception{ Response response = validateMsisdnHandlerIRSpy.validate(validate,messageControl); } 
0
source share
1 answer

Replace

ValidateHandlerSoapClient soapClientSpy = PowerMockito.spy( new ValidateHandlerSoapClient())

from

ValidateHandlerSoapClient soapClientMock = PowerMockito.mock(ValidateHandlerSoapClient.class)

The default spy simply calls the methods of the base regular class. What you want to do (presumably) is nothing when soap client methods are called.

Then, of course, you will also need to change:

.

PowerMockito.whenNew (ValidateHandlerSoapClient.class) .withNoArguments () thenReturn (soapClientMock);

0
source

Source: https://habr.com/ru/post/1011766/


All Articles