2012-04-07 13 views
4

EasyMockとEasyMock CE 3.0を使用して依存レイヤをモックし、クラスをテストしています。以下は私が解決策を見つけることができないシナリオですEasyMockを使用してvoidメソッドに渡されたparamsに期待値を設定する方法

私は従属クラスを呼び出すクラスを持っています入力パラメータをとり、同じパラメータを変更するを変更するメソッドです。私がテストしていメソッドは、私はさまざまなシナリオ

のために今テストする必要が変更されたのparamに基づいていくつかの操作を、やっている私は、同じシナリオを入れしようとした以下のサンプルを、考えてみましょう

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"); 
} 

は、私は真と偽が返されるの両方のシナリオをテストするために、2のテストケースを持っている必要がありますが、私は設定することはできませんよ、私は常にfalseを取得しますこの入力を変更するvoidメソッドの動作 豆。このシナリオでEasyMockを使用して真の結果を得るにはどうすればいいですか

ありがとうございました。

答えて

6

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 
2

おかげで..私は問題は解決してしまった...あまりにもサンプルコードについて:) 感謝。上記のコードを使用して

は、私がしなければならなかった1つの変更は、テスト対象の方法で更新Beanを取得することができ、このAMで

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

です。

もう一度お手数をおかけします。

関連する問題