在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) {
...
}
当我调试时,我看到resreceipt不是null,与resreceipt.getResponseCode()相同,但在这一行上执行un Null Pointer Exception。
真实价值与模拟?
似乎对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);
答案 0 :(得分:0)
基本上,您需要在代码中创建seam,您可以在不改变代码本身的情况下更改代码的行为。本质上,您注入依赖项,而不是让代码实例化依赖项,以便您可以在测试时模拟依赖项。目前,在您的测试代码中,您被迫使用resAddCC
和mpgReq
的实际值,因为当前的生产代码通过new
关键字实例化它们,而不是使用注入工厂,然后在工厂对象上调用工厂方法。使用这样的工厂,您可以模拟工厂及其调用,否则它将调用Moneris。