MockitoJUnitRunnerフレームワークの使用状況の自動検証と、自動を提供しますinitMocks()。
フレームワークの使用法の自動検証は、実際に行う価値があります。これらの間違いのいずれかを行った場合、より適切なレポートが得られます。
静的whenメソッドを呼び出しますが、一致するthenReturn、thenThrowまたはでスタブを完了しないでくださいthen。 (以下のコードのエラー1)
モックを呼び出しverifyますが、検証しようとしているメソッド呼び出しを提供するのを忘れています。(以下のコードのエラー2)
の後にwhenメソッドを呼び出すか
、モックを渡しますが、スタブしようとしているメソッドを指定するのを忘れてください。 (以下のコードのエラー3)doReturndoThrowdoAnswer
フレームワークの使用法の検証がない場合、これらの間違いは、次のMockitoメソッドの呼び出しまで報告されません。これは
- 同じテスト方法(以下のエラー1など)で、
- 次のテスト方法(以下のエラー2など)では、
- 次のテストクラスで。
実行した最後のテストで発生した場合(以下のエラー3のように)、それらはまったく報告されません。
これらのタイプのエラーのそれぞれがどのように見えるかを次に示します。ここで、JUnitがこれらのテストをここにリストされている順序で実行するとします。
@Test
public void test1() {
// ERROR 1
// This compiles and runs, but it's an invalid use of the framework because
// Mockito is still waiting to find out what it should do when myMethod is called.
// But Mockito can't report it yet, because the call to thenReturn might
// be yet to happen.
when(myMock.method1());
doSomeTestingStuff();
// ERROR 1 is reported on the following line, even though it's not the line with
// the error.
verify(myMock).method2();
}
@Test
public void test2() {
doSomeTestingStuff();
// ERROR 2
// This compiles and runs, but it's an invalid use of the framework because
// Mockito doesn't know what method call to verify. But Mockito can't report
// it yet, because the call to the method that's being verified might
// be yet to happen.
verify(myMock);
}
@Test
public void test3() {
// ERROR 2 is reported on the following line, even though it's not even in
// the same test as the error.
doReturn("Hello").when(myMock).method1();
// ERROR 3
// This compiles and runs, but it's an invalid use of the framework because
// Mockito doesn't know what method call is being stubbed. But Mockito can't
// report it yet, because the call to the method that's being stubbed might
// be yet to happen.
doReturn("World").when(myMock);
doSomeTestingStuff();
// ERROR 3 is never reported, because there are no more Mockito calls.
}
5年以上前にこの答えを最初に書いたとき、私は
したがって、MockitoJUnitRunner可能な限り使用することをお勧めします。ただし、Tomasz Nurkiewiczが正しく指摘しているように、Springなどの別のJUnitランナーが必要な場合は使用できません。
私の推薦は今変わりました。私がこの回答を最初に書いたときから、Mockitoチームは新しい機能を追加しました。これはJUnitルールであり、とまったく同じ機能を実行しMockitoJUnitRunnerます。しかし、他のランナーの使用を妨げるものではないので、それはより良いことです。
含む
@Rule
public MockitoRule rule = MockitoJUnit.rule();
テストクラスで。これにより、モックが初期化され、フレームワークの検証が自動化されます。と同じようMockitoJUnitRunnerに。しかし今では、SpringJUnit4ClassRunnerまたは他のJUnitRunnerも使用できます。Mockito 2.1.0以降、報告される問題の種類を正確に制御する追加のオプションがあります。