Spring Mockito模拟基于构造函数的api调用
我有以下服务,它有一个调用第三方api的executeSofortRequestSpring Mockito模拟基于构造函数的api调用,spring,spring-boot,mockito,Spring,Spring Boot,Mockito,我有以下服务,它有一个调用第三方api的executeSofortRequest @RequiredArgsConstructor public class SofortRequestService { public com.sofort.lib.payment.products.response.PaymentResponse executeSofortRequest(com.sofort.lib.payment.products.request.PaymentRequest sofortR
@RequiredArgsConstructor
public class SofortRequestService {
public com.sofort.lib.payment.products.response.PaymentResponse executeSofortRequest(com.sofort.lib.payment.products.request.PaymentRequest sofortRequest,
ExternalPaymentInfoEntity externalPaymentInfo) {
com.sofort.lib.payment.products.response.PaymentResponse sofortResponse;
try {
sofortResponse = new DefaultSofortLibPayment(customerId, apiKey).sendPaymentRequest(sofortRequest);
} catch (HttpAuthorizationException e) {
saveExternalPaymentInfo(externalPaymentInfo, e);
throw new ResponseStatusException(HttpStatus.INTERNAL_SERVER_ERROR, SOFORT_AUTHORIZATION_FAILED_WITH_GIVEN_APIKEY, e);
} catch (ConnectionException e) {
saveExternalPaymentInfo(externalPaymentInfo, e);
throw new ResponseStatusException(HttpStatus.INTERNAL_SERVER_ERROR, SOFORT_COMMUNICATION_FAILED, e);
}
return sofortResponse;
}
}
现在我在考试中模仿了这个
@RunWith(MockitoJUnitRunner.class)
public class SofortRequestServiceTest {
@Mock
private ExternalPaymentInfoRepository externalPaymentInfoRepository;
@InjectMocks
private SofortRequestService sofortRequestService;
@Test
public void test_executeSofortRequest() throws JsonProcessingException {
given(new DefaultSofortLibPayment(1234, "test-api-key").sendPaymentRequest(sofortPaymentRequest)).willThrow(HttpAuthorizationException.class);
//When
assertThatThrownBy(() -> sofortRequestService.executeSofortRequest(sofortPaymentRequest, externalPaymentInfoEntity))
.isInstanceOf(HttpAuthorizationException.class);
//Then
verify(externalPaymentInfoRepository, times(1))
.save(ExternalPaymentInfoEntity.builder()
.referenceTransaction(paymentRequest.getTransactionId())
.customerId(paymentRequest.getPaymentDocument()
.getCustomer()
.getCustomerId())
.eventType(OUTGOING)
.paymentType("sofort checkout")
.action(AUTH)
.requestData(new ObjectMapper().writeValueAsString(paymentRequest))
.success(false)
.build());
}
}
我的问题是当测试执行并运行时
给定(新的DefaultSofortLibPayment(1234,“测试api密钥”).sendPaymentRequest(sofortPaymentRequest)).willThrow(HttpAuthorizationException.class);
它运行的是实际的实现,而不是模拟,然后它无法进一步执行。
如何为
executesfortrequest
方法编写集成测试这可能不是您想要的答案,
但在您的情况下,我会添加一个包访问零(0)参数构造函数
作为在单元测试期间支持模拟的一种方式
在这种情况下,,
确保单元测试与它所测试的类在同一个包中。你应该考虑
@Autowire
而不是用new
关键字new DefaultSofortLibPayment(1234,“test api key”)
创建对象,为什么不使用mock呢?你需要一种注入mock的方法-例如提取创建方法。