【发布时间】:2020-05-06 16:59:08
【问题描述】:
这是我正在尝试测试的方法 -
@Service
public class ShareableLinkService {
private PaymentService paymentService;
@Autowired
public ShareableLinkService(PaymentService paymentService) {
this.paymentService = paymentService;
}
public ResponseEntity<ResponseDTO> cancelSmartPay(Long id, String merchantRefId) {
..
responseDTO = paymentService.processCancelPayment(id, merchantRefId);
..
}
}
下面是被调用的方法——
@Service
public class PaymentService {
@Transactional
public ResponseDTO processCancelPayment(Long param, String merchantRefId) {
TransactionRequest transactionRequest = transactionRequestService.findByMerchantIdAndMerchantRefId(param, merchantRefId);
..
}
以下是我的测试代码-
@RunWith(MockitoJUnitRunner.class)
public class SmartPayMockitoServiceTest {
@Mock
private PaymentService paymentServiceNew;
when(paymentServiceNew.processCancelPayment(id,merchantRefId)).thenReturn(new ResponseDTO(Constants.API_RESPONSE_SUCCESS, "transaction cancelled"));
when(paymentServiceNew.processCancelPayment(id,merchantRefId)).thenReturn(new ResponseDTO(Constants.API_RESPONSE_SUCCESS, "transaction cancelled"));
assertEquals("1", shareableLinkService.cancelSmartPay(id, merchantRefId).getBody().getStatus().toString());
assertEquals("1", shareableLinkService.cancelSmartPay(payoutMerchantId, merchantRefId).getBody().getStatus().toString());
当我在最后一条语句中运行 cancelSmartPay() 调用时,它实际上调用了 processCancelPayment() 方法。
我已经查过了Mockito when().thenReturn calls the method unnecessarily
更新
我按照@Jalil 的回答做了 -
@Mock
private PaymentService paymentService;
@InjectMocks
private ShareableLinkService shareableLinkService;
然而,实际的方法仍然被调用。另外,当我处于调试模式时,我会收到一个java.lang.reflect.InvocationTargetException。
【问题讨论】:
-
您向我们展示了如何实例化模拟。您如何创建被测服务?
-
@Lesiak 在更新中添加
-
到目前为止一切正常。没有看到整个测试很难说。
-
您需要确保 shareableLinkService 对象是 1) 模拟对象或 2) 具有被存根的函数 cancelSmartPay() 的间谍对象。
标签: spring spring-boot unit-testing junit mockito