gpt4 book ai didi

java - 外部模拟方法在实际类中返回 Null

转载 作者:太空宇宙 更新时间:2023-11-04 07:51:51 35 4
gpt4 key购买 nike

当我测试模拟外部调用时,我没有看到报告的模拟值,而是 Null 并且我的测试失败。我可以在测试类中看到(报告的)模拟值,但在 BusinessServiceImpl 类中看不到,并且应用程序(方法返回)未按我的预期进行修改。

我的期望:当我在 Impl 类中模拟外部调用时,模拟值应该在那里可用,并且其他所有事情都会发生,就像调用真实方法来完成单元测试一样。

实现代码:

package com.core.business.service.dp.fulfillment;

import com.core.business.service.dp.payment.PaymentBusinessService;

public class BusinessServiceImpl implements BusinessService { // Actual Impl Class
private PaymentBusinessService paymentBusinessService = PluginSystem.INSTANCE.getPluginInjector().getInstance(PaymentBusinessService.class);

@Transactional( rollbackOn = Throwable.class)
public Application applicationValidation (final Deal deal) throws BasePersistenceException {
Application application = (Application) ApplicationDTOFactory.eINSTANCE.createApplication();
//External Call we want to Mock
String report = paymentBusinessService.checkForCreditCardReport(deal.getId());
if (report != null) {
application.settingSomething(true); //report is Null and hence not reaching here
}
return application;
}
}

测试代码:

@Test(enabled = true)// Test Class
public void testReCalculatePrepaids() throws Exception {
PaymentBusinessService paymentBusinessService = mock(PaymentBusinessService.class);
//Mocking External Call
when(paymentBusinessService.checkForCreditCardReport(this.deal.getId())).thenReturn(new String ("Decline by only Me"));
String report = paymentBusinessService.checkForCreditCardReport(this.deal.getId());
// Mocked value of report available here
//Calling Impl Class whose one external call is mocked
//Application is not modified as expected since report is Null in Impl class
Application sc = BusinessService.applicationValidation(this.deal);
}

最佳答案

Mockito 的主要目的是隔离测试。例如,当您测试 BusinessServiceImpl 时,您应该模拟其所有依赖项。

这正是您在上面的示例中尝试执行的操作。现在,为了让模拟发挥作用,必须将模拟对象注入(inject)到您尝试测试的类中,在本例中为 BusinessServiceImpl。

实现此目的的一种方法是通过类的构造函数 dependency injection 传递依赖关系。 。或者你可以看看如何用 Spring and ReflectionTestUtils. 来完成

关于java - 外部模拟方法在实际类中返回 Null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14322645/

35 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com