首页 > 解决方案 > Mockito when().thenReturn 调用实际方法

问题描述

这是我正在尝试测试的方法 -

@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 不必要地调用该方法

更新

我按照@Jalil的回答做了它-

@Mock
private PaymentService paymentService;


@InjectMocks
private ShareableLinkService shareableLinkService;

但是,仍然调用了实际的方法。此外,当我处于调试模式时,我得到一个java.lang.reflect.InvocationTargetException.

标签: springspring-bootunit-testingjunitmockito

解决方案


你能分享一下你是如何实例化shareableLinkService对象的吗?

它应该是这样的

@RunWith(MockitoJUnitRunner.class)
public class SmartPayMockitoServiceTest {

    @Mock
    private PaymentService paymentServiceNew;

    @InjectMocks
    private ShareableLinkService shareableLinkService;

    // the rest of the code

}

您的测试应该在使用 @Test 注释的方法中

@Test
void testMethod(){

    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());

}

推荐阅读