问题
paymentBusinessService class is avaiable in BusinessService class dependency injection. The Application sc = Applicaition.applicationValidation(this.deal); suppose to be
Application sc = BusinessService.applicationValidation(this.deal);
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);
}
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());
//Calling Impl Class whose one external call is mocked
Application sc = BusinessService.applicationValidation(this.deal);
}
回答1:
It is not clear how your Application class references the PaymentBusinessService. I'm guessing that your Application class has a static reference to a PaymentBusinessService. In that case, you must make sure that reference points to the mock you are creating.
Update
Given that your PaymentBusinessService is a private field which is not initialized in the constructor, you'll need to reflectively inject your mock object into your Application class.
回答2:
Thanks Aurand for giving me the idea of injecting mock object into application class. Using @InjectMock works fine.
@MOCK
PaymentBusinessService paymentBusinessService;
@InjectMock
Application application = PluginSystem.INSTANCE.getPluginInjector().getInstance(Application.class);
@Test(enabled = true)// Test Class
public void testReCalculatePrepaids() throws Exception {
//Mocking External Call
when(paymentBusinessService.checkForCreditCardReport(this.deal.getId())).thenReturn(new String("Decline by only Me"));
String report = paymentBusinessService.checkForCreditCardReport(this.deal.getId());
//Calling Impl Class whose one external call is mocked
Application sc = BusinessService.applicationValidation(this.deal);
来源:https://stackoverflow.com/questions/14269502/how-do-i-mock-external-method-call-with-mockito