Raghu
Raghu

Reputation: 69

How to mock web service call without passing mocked class as parameter

I have a web serivce class which need to unit tested. Here is class which is under test

public class ValidatePaymentMessage {

public CsmValidationResultX validatePaymentmsg(String csmName, String base64PayloadXML){
      //Call Web Service to validate Payment
    CsmValidationResultX responseMsg=null;
    PaymentManagerWebService paymentManagerWebService = new PaymentManagerWebService();
    PaymentManagerWebServiceImpl serviceAddrs = paymentManagerWebService.getPaymentManagerWebServicePort();
    try {
         responseMsg = serviceAddrs.validatePayment(csmName, base64PayloadXML);
    } catch (MPMWebServiceException e) {

        e.printStackTrace();
    }

    return responseMsg;
   }
}

Here is my Junit class

public class ValidatePaymentMessageTest {

@Test
public void testValidatePaymentmsg() throws MPMWebServiceException {

    CsmValidationResultX csmResult= EasyMock.createMock(CsmValidationResultX.class);

    PaymentManagerWebServiceImpl paymentManagerImpl = EasyMock.createMock(PaymentManagerWebServiceImpl.class);
    EasyMock.expect(paymentManagerImpl.validatePayment("SEPA","BASE64XML")).andReturn(csmResult).anyTimes();

    PaymentManagerWebService paymentManager = EasyMock.createMock(PaymentManagerWebService.class);
    EasyMock.expect(paymentManager.getPaymentManagerWebServicePort()).andReturn(paymentManagerImpl).anyTimes();

    ValidatePaymentMessage validatePayment=new ValidatePaymentMessage();
    CsmValidationResultX response = validatePayment.validatePaymentmsg("SEPA", "base64PayloadXML");
    System.out.println(response.getCsmValidationResult().isValid());
 }

}

When I run this Junit it is calling actual web service instead of mocked one's.So Please let me know how can i resolve this problem.

Upvotes: 0

Views: 75

Answers (1)

vempo
vempo

Reputation: 3153

You are still instantiating a real PaymentManagerWebService in validatePaymentmsg(), so the mocks do not help. You can't mock construction of local variables with EasyMock, but you can with PowerMock. So if changing the code to receive and instance of PaymentManagerWebService is not an option, mock its construction with PowerMock.

@RunWith(PowerMockRunner.class)
@PrepareForTest(ValidatePaymentMessage.class)
public class ValidatePaymentMessageTest {

    @Test
    public void testValidatePaymentmsg() throws MPMWebServiceException {

        // .....
        PowerMock.expectNew(PaymentManagerWebService.class).andReturn(paymentManager);
        //....
    }
}

Upvotes: 1

Related Questions