Powermock模拟其他执行方法调用的实例方法 [英] Powermock to mock instance methods called from other executing methods

查看:1224
本文介绍了Powermock模拟其他执行方法调用的实例方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在这段代码中,我模拟了ValidateHandlerSoapClient类方法之一,该方法已实例化并在validateMsisdnHandlerIRSpy.validate()中将此方法称为(soapClientSpy.processSoapRequestRespons).so soapClientSpy.processSoapRequestResponse无法正常工作,而是将实际方法称为。

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

    }


推荐答案

替换

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

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

这篇关于Powermock模拟其他执行方法调用的实例方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆