4

EasyMock と EasyMock CE 3.0 を使用して依存レイヤーをモックし、クラスをテストしています。以下は、解決策を見つけることができないシナリオです

テストするクラスがあります。これは、入力パラメーターを受け取り、同じ param を変更する依存クラスの void メソッドを呼び出します。私がテストしているメソッドは、変更されたパラメーターに基づいていくつかの操作を実行しています。これは、さまざまなシナリオで今テストする必要があります

同じシナリオを入れようとした以下のサンプルを考えてみましょう

public boolean voidCalling(){
    boolean status = false;
    SampleMainBean mainBean = new SampleMainBean();
    dependentMain.voidCalled(mainBean);
    if(mainBean.getName() != null){
        status = true; 
    }else{
        status = false;
    }
    return status;
}

そしてdependentMainクラスは以下のメソッド

public void voidCalled(SampleMainBean mainBean){
    mainBean.setName("Sathiesh");
}

完全なカバレッジを得るには、true と false が返される両方のシナリオをテストする 2 つのテスト ケースが必要ですが、void メソッドの動作を設定してこの入力 Bean を変更することができないため、常に false になります。EasyMock を使用して、このシナリオの結果として true を取得するにはどうすればよいですか

助けてくれてありがとう。

4

2 に答える 2

7

この回答EasyMock: Void Methodsの回答から始めて、 IAnswerを使用できます。

// create the mock object
DependentMain dependentMain = EasyMock.createMock(DependentMain.class);

// register the expected method
dependentMain.voidCalled(mainBean);

// register the expectation settings: this will set the name 
// on the SampleMainBean instance passed to voidCalled
EasyMock.expectLastCall().andAnswer(new IAnswer<Object>() {
    @Override
    public Object answer() throws Throwable {
        ((SampleMainBean) EasyMock.getCurrentArguments()[0])
                .setName("Sathiesh");
        return null; // required to be null for a void method
    }
});

// rest of test here
于 2012-04-11T09:59:05.657 に答える
2

お返事ありがとうございます。問題は解決しました... :) サンプル コードもありがとうございます。

上記のコード スニペットを使用して、私がしなければならなかった 1 つの変更は、

// register the expected method
dependentMain.voidCalled((SampleMainBean) EasyMock.anyObject());

これにより、テスト対象のメソッドで更新された Bean を取得できます。

ご協力いただきありがとうございます。

于 2012-04-14T10:41:15.657 に答える