如何使用Mockito模拟外部方法调用

时间:2013-01-11 00:01:05

标签: java junit testng mockito powermock

paymentBusinessService类可用于BusinessService类依赖注入。应用程序sc = Applicaition.applicationValidation(this.deal);假设是 应用程序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);  

}

2 个答案:

答案 0 :(得分:0)

目前尚不清楚Application类如何引用PaymentBusinessService。我猜你的Application类有一个对PaymentBusinessService的静态引用。在这种情况下,您必须确保引用指向您正在创建的模拟。

<强>更新

鉴于您的PaymentBusinessService是一个未在构造函数中初始化的私有字段,您需要反射性地将模拟对象注入到您的Application类中。

答案 1 :(得分:0)

感谢Aurand给我一个将mock对象注入应用程序类的想法。使用@InjectMock工作正常。

@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);