2017-09-29 5 views
-1

シナリオユニットテスト - 保護されたメソッドからブール値をスタブするにはどうすればいいですか?だからここ

public class Report { 

    public void Generate { 
     if (!isValidDate) { 
     return; 
     } 

     //calling other method 
    } 

    protected boolean isValidDate() { 
     boolean isValid = true; 
     //some logic here to change to false 
     return isValid; 
    } 
} 

そして、私のテストである私が真実であるとブール値を設定したいと、私はこれを持っています。

@InjectMocks 
Report report; 

@Before 
public void setUp() throws Exception { 
    Whitebox.setInternalState(report, "isValidParameters", true); 
} 

@Test 
public void testReport() throws Exception { 
    //test logic to be added here 
} 

私はRuntimeExceptionを取得しました。プライベートフィールドに内部状態を設定できません。誰かがここに私のテストのための保護されたメソッドのブール値を設定する方法について助けてもらえますか? TIA

答えて

0

単体テストの書き方を学びたい場合は、の使用を中止するとよいでしょう。

自分でテストしたい保護された方法は、クラスの責任が過度にあり、リファクタリングする必要があるという兆候です。

このメソッドの代わりに、抽出オブジェクトパターンを使用してみませんか?

public class DateValidator { 
    public boolean isValid(Date date) { 
     //previous logic from protected method goes here 
    } 
} 

次に、あなたのクラスのコンストラクタにこれを渡すことができます。

public class Report { 

    private final DateValidator dateValidator; 

    public Report(DateValidator dateValidator) { 
     this.dateValidator = dateValidator; 
    } 
} 

を今すぐあなたのテストは次のようになります。プレーンMockitoにこだわっ

@Mock DateValidator mockDateValidator; 

//system under test 
Report report; 

@Before 
public void setUp() { 
    MockitoAnnotations.initMocks(this); 
    report = new Report(mockDateValidator); 
} 

@Test 
public void test() throws Exception { 
    when(mockDateValidator.isValid()).thenReturn(true); 

    //your test here 
} 

があることは良い規律あります良いOOPの実践を教えてくれるでしょう。 Mocktioのドキュメントはこれを説明するのに非常に良いものであり、あなたはそれを読むことによって多くの利益を得ることができます。

関連する問題