当我测试Mocked外部调用时,我没有看到报告的模拟值而是Null
并且我的测试失败了。我可以在Test Class中看到Mocked值(报告)但不在BusinessServiceImpl
类中看到,而Application(Method Return)不会像我预期的那样被修改。
我的期望:当我在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);
}
答案 0 :(得分:1)
Mockito的主要目的是隔离测试。在测试你的BusinessServiceImpl
时,你应该模拟它的所有依赖项。
这正是您尝试使用上面的示例所做的。现在要使 mocking 工作,必须将模拟对象注入到您要测试的类中,在本例中为BusinessServiceImpl
。
这样做的一种方法是通过类的构造函数dependency injection传递dependecy。或者您可以查看如何使用Spring
and ReflectionTestUtils
.
答案 1 :(得分:0)
我完成了它并且我成功地获得了Mocked值而根本没有触及BusinessServiceImpl类。我遵循的步骤是: 1. @Mock PaymentBusinessService paymentBusinessService = mock(PaymentBusinessService.class); 2. @InjectMocks private PaymentBusinessService paymentBusinessService = PluginSystem.INSTANCE.getPluginInjector()。getInstance(PaymentBusinessService.class);
然后简单地运行上面的测试,我可以在BusinessServiceImpl中看到报告的值为“仅由我拒绝”并且我的测试用例已通过