1

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

我的期望:当我在 Impl 类中模拟 External 调用时,模拟值应该在那里可用,其余的一切都会发生,就好像调用了真正的方法来完成单元测试一样。

实现代码:

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);
}
4

2 回答 2

1

Mockito 的主要目的是隔离测试。就像在测试时一样,BusinessServiceImpl你应该模拟它的所有依赖项。

这正是您在上面的示例中尝试做的事情。现在要使模拟工作,必须将模拟对象注入到您要测试的类中,在本例中为BusinessServiceImpl.

一种方法是通过类的构造函数传递依赖关系,依赖注入。或者您可以看看如何使用Springand来完成ReflectionTestUtils

于 2013-01-14T18:37:55.460 回答
0

我完成了它,我成功地获得了 Mocked 值,而根本不接触 BusinessServiceImpl 类。我遵循的步骤是: 1. @Mock PaymentBusinessService paymentBusinessService = mock(PaymentBusinessService.class); 2. @InjectMocks private PaymentBusinessService paymentBusinessService = PluginSystem.INSTANCE.getPluginInjector().getInstance(PaymentBusinessService.class);

然后简单地运行上面的测试,我可以在 BusinessServiceImpl 中看到报告的值“只有我拒绝”,我的测试用例通过了

于 2013-01-23T21:23:03.067 回答