1

モックされた外部呼び出しをテストしているとき、レポートのモックされた値が表示されNullず、テストが失敗しています。(レポートの) Mocked 値が Test Class に表示されますが、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);
}
4

2 に答える 2

1

Mockito の主な目的は、テストを分離することです。のように、テストするときは、BusinessServiceImplすべての依存関係をモックする必要があります。

これはまさに、上記の例でやろうとしていることです。モックを機能させるには、モックされたオブジェクトを、テストしようとしているクラス (この場合はBusinessServiceImpl.

これを行う 1 つの方法は、クラスのコンストラクターである依存性注入によって依存関係を渡すことです。または、とを使用してそれを行う方法を確認することもできますSpringReflectionTestUtils

于 2013-01-14T18:37:55.460 に答える
0

私はそれをやり遂げ、BusinessServiceImpl クラスにまったく触れずに Mocked 値を正常に取得できました。私が従った手順は次のとおりです。 1. @Mock PaymentBusinessService paymentBusinessService = mock(PaymentBusinessService.class); 2. @InjectMocks プライベート PaymentBusinessService paymentBusinessService = PluginSystem.INSTANCE.getPluginInjector().getInstance(PaymentBusinessService.class);

そして、単純に上記のテストを実行すると、Report の値が BusinessServiceImpl で "Decline by only Me" として表示され、テスト ケースに合格したことがわかりました。

于 2013-01-23T21:23:03.067 に答える