我有一个需要进行单元测试的web服务类。 这是正在测试的课程
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;
}
}
这是我的Junit课程
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());
}
}
当我运行这个Junit时,它正在调用实际的Web服务而不是模拟的人。所以请让我知道如何解决这个问题。
答案 0 :(得分:1)
您仍然在validatePaymentmsg()中实例化一个真实的PaymentManagerWebService,因此模拟没有帮助。您不能使用EasyMock模拟局部变量的构造,但您可以使用PowerMock。因此,如果不能选择将代码更改为接收和PaymentManagerWebService实例,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);
//....
}
}