无法正确模拟



在Spring-Boot应用程序中,我致电Moneris。我想模拟这部分。

在服务类中:

@Transactional
@Override
public void saveCreditCard(CreditCardInfoDto creditCardInfo) throws CreditCardException, ResourceNotFoundException {
     ...
     ResolveData resdata = null;
     ResolverReceipt resreceipt = null;
     ...
     ResAddCC resAddCC = new ResAddCC(creditCardInfo.getCreditCard(), expirationDate, String.valueOf(paymentGateway.getCryptType()));
     resAddCC.setCustId(member.getMemberId().toString());

     ResolverHttpsPostRequest mpgReq = new ResolverHttpsPostRequest(paymentGateway.getHost(), paymentGateway.getStoreId(), paymentGateway.getApiToken(), resAddCC);
     resreceipt = mpgReq.getResolverReceipt();
     resdata = resreceipt.getResolveData();
                ...
     if (resreceipt != null && resreceipt.getResponseCode() != null && Integer.getInteger(resreceipt.getResponseCode()) < 50) {
                   ...
     }

当我调试时,我会看到recreceipt不是null,与resReceipt.getResponsecode()相同,但在此行上确实没有null指针例外。

实际价值与模拟?

似乎对Moneris进行了不真实的电话...我想避免。

在我的课程测试中,我有:

@InjectMocks
PaymentServiceImpl paymentService;
@Mock
MemberRepository memberRepository;
@Mock
PaymentGatewayConfigRepository paymentGatewayConfigRepository;
@Mock
OperationRepository operationRepository;
@Mock
ResolverReceipt resreceipt;
@Mock
ResolverHttpsPostRequest mpgReq;
@Before
public void initMocks() {
    MockitoAnnotations.initMocks(this);
}
 Mockito.when(memberRepository.findOne(memberId)).thenReturn(member);
    Mockito.when(paymentGatewayConfigRepository.findAll()).thenReturn(paymentsGateway);
    ResolverReceipt resreceipt = new ResolverReceipt("<?xml version="1.0" encoding="UTF-8"?> <receipt>   <DataKey>iZxTfRWZaRd3S2lajvoZaPA22</DataKey>   <ReceiptId>null</ReceiptId>   <ReferenceNum>null</ReferenceNum>   <ResponseCode>001</ResponseCode>   <ISO>null</ISO>   <AuthCode>null</AuthCode>   <Message>Successfully registered CC details.</Message>   <TransTime>19:13:52</TransTime>   <TransDate>2016-12-09</TransDate>   <TransType>null</TransType>   <Complete>true</Complete>   <TransAmount>null</TransAmount>   <CardType>null</CardType>   <TransID>null</TransID>   <TimedOut>false</TimedOut>   <CorporateCard>null</CorporateCard>   <RecurSuccess>null</RecurSuccess>   <AvsResultCode>null</AvsResultCode>   <CvdResultCode>null</CvdResultCode>   <ResSuccess>true</ResSuccess>   <PaymentType>cc</PaymentType>   <IsVisaDebit>null</IsVisaDebit>   <ResolveData>     <cust_id>1</cust_id>     <phone>4506777244</phone>     <email>paul.smith@gmail.com</email>     <note></note>     <crypt_type>0</crypt_type>     <masked_pan>4242***4242</masked_pan>     <expdate>1601</expdate>   </ResolveData> </receipt> ");

    Mockito.when(mpgReq.getResolverReceipt()).thenReturn(resreceipt);

基本上,您需要在代码中创建一个接缝,可以在其中更改代码的行为而不更改代码本身。从本质上讲,您注入依赖性,而不是让代码实例化依赖项,以便在测试时可以模拟依赖项。目前,在您的测试代码中,您不得不使用resAddCCmpgReq的实际值,因为当前的生产代码通过new关键字实例化,而不是使用注射的工厂,然后在工厂对象上调用工厂方法。使用这样的工厂,您可以嘲笑工厂及其电话,否则它可以在其中拨打Moneris。

相关内容

  • 没有找到相关文章

最新更新