Powermock模拟从其他执行方法调用的实例方法

时间:2014-08-06 12:44:02

标签: mockito powermock

在这段代码中,我模拟了一个ValidateHandlerSoapClient类方法,该方法在validateMsisdnHandlerIRSpy.validate()中被实例化并调用了这个方法(soapClientSpy.processSoapRequestRespons)。所以soapClientSpy.processSoapRequestResponse不起作用,而是调用了真正的方法

@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 个答案:

答案 0 :(得分:0)

替换

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

ValidateHandlerSoapClient soapClientMock = PowerMockito.mock(ValidateHandlerSoapClient.class)

默认情况下,间谍只调用底层常规类的方法。当你调用soap客户端的方法时,你想做的事情(推测)是没有的。

当然,你还需要改变:

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