mockito
モッキートのベストプラクティス
サーチ…
BDDMockitoスタイル
Behavior Driven Development(BDD)のテストスタイルは、テストの「与えられた」、「いつ」、「いつ」のステージを中心に展開されています。しかし、古典的なMockitoは、「与えられた」段階の「時」の単語を使用し、BDDを包含する他の自然言語の構造は含まない。したがって、 BDDMockitoエイリアスは、動作駆動テストを容易にするためにバージョン1.8.0で導入されました。
最も一般的な状況は、メソッドの返り値をスタブすることです。次の例では、 givenName
と等しい引数で呼び出された場合new Student(givenName, givenScore)
StudentRepository
getStudent(String)
メソッドはnew Student(givenName, givenScore)
を返しgivenName
。
import static org.mockito.BDDMockito.*;
public class ScoreServiceTest {
private StudentRepository studentRepository = mock(StudentRepository.class);
private ScoreService objectUnderTest = new ScoreService(studentRepository);
@Test
public void shouldCalculateAndReturnScore() throws Exception {
//given
String givenName = "Johnny";
int givenScore = 10;
given(studentRepository.getStudent(givenName))
.willReturn(new Student(givenName, givenScore));
//when
String actualScore = objectUnderTest.calculateStudentScore(givenName);
//then
assertEquals(givenScore, actualScore);
}
}
場合によっては、依存関係からスローされた例外が、正しく処理されているか、テスト中のメソッドで再スローされているかどうかを確認することが望まれます。そのような振る舞いは、このようにして「与えられた」段階で突き止められます:
willThrow(new RuntimeException())).given(mock).getData();
時には、スタブされたメソッドが導入すべきいくつかの副作用を設定することが望まれます。特に次の場合に便利です。
stubbedメソッドは、渡されたオブジェクトの内部状態を変更するはずのメソッドです
スタブ付きメソッドはvoidメソッドです
そのような振る舞いは、「回答」を伴う「与えられた」段階で突き止められます:
willAnswer(invocation -> this.prepareData(invocation.getArguments()[0])).given(mock).processData();
モックとのやりとりを検証する必要がある場合は、 should()
またはshould(VerificationMode)
)メソッド(1.10.5以降のみ)を使用して「then」フェーズで実行できます。
then(mock).should().getData(); // verifies that getData() was called once
then(mock).should(times(2)).processData(); // verifies that processData() was called twice
すでに検証済みではなく模擬とのやりとりがなくなったことを確認したいときは、 shouldHaveNoMoreInteractions()
(2.0.0以降shouldHaveNoMoreInteractions()
で "then"フェーズで行うことができます:
then(mock).shouldHaveNoMoreInteractions(); // analogue of verifyNoMoreInteractions(mock) in classical Mockito
モックとのやりとりが全くないことを確認したいときは、 shouldHaveNoMoreInteractions()
(2.0.0以降shouldHaveNoMoreInteractions()
で "then"フェーズで行うことができます:
then(mock).shouldHaveZeroInteractions(); // analogue of verifyZeroInteractions(mock) in classical Mockito
メソッドが呼び出されたかどうかをチェックしたい場合は、 should(InOrder)
(1.10.5以降should(InOrder)
で "then"フェーズでshould(InOrder, VerificationMode)
(2.0.0以降)
InOrder inOrder = inOrder(mock);
// test body here
then(mock).should(inOrder).getData(); // the first invocation on the mock should be getData() invocation
then(mock).should(inOrder, times(2)).processData(); // the second and third invocations on the mock should be processData() invocations