当我测试模拟外部调用时,我没有看到报告的模拟值,而是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
时,应该模拟它的所有依赖项。
这正是你在上面的例子中想要做的。现在要使mock 起作用,必须将mock对象注入您要测试的类中,在本例中为BusinessServiceImpl
。
Spring
和ReflectionTestUtils
是如何做到的。
我完成了它,我成功地获得了mock值,而完全没有触及BusinessServiceImpl类。我遵循的步骤是:1. @Mock PaymentBusinessService = mock(PaymentBusinessService.class);2. @ injectmock private PaymentBusinessService = PluginSystem.INSTANCE.getPluginInjector().getInstance(PaymentBusinessService.class);
然后简单地运行上面的测试,我可以在BusinessServiceImpl中看到报告的值为"Decline by only Me",我的测试用例通过了