Powermock to mock instance methods called from other executing methods

给你一囗甜甜゛ 提交于 2019-12-12 01:59:27

问题


In this code, i have mocked the one of the ValidateHandlerSoapClient class method which is instantiated and called this method (soapClientSpy.processSoapRequestRespons) in validateMsisdnHandlerIRSpy.validate().So soapClientSpy.processSoapRequestResponse is not working , instead the real method is called.

@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);

    }

回答1:


Replace

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

with

ValidateHandlerSoapClient soapClientMock = PowerMockito.mock(ValidateHandlerSoapClient.class)

A spy by default just calls the methods of the underlying regular class. What you want to do is (presumably) nothing when the methods of the soap client are called.

Then of course you will need to make also change:

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



来源:https://stackoverflow.com/questions/25160761/powermock-to-mock-instance-methods-called-from-other-executing-methods

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!