基本
Mockしたクラスのメソッドが呼ばれることのテスト
@ExtendWith(MockitoExtension.class)
public class IndexSelectScanTest {
@Mock
private User user; // mockしたいClass
@Test
public void testMock() {
Example expl = new Example(user);
expl.doSomethingForUser(); // ExampleのdoSomethingForUser()メソッドをコール
verify(user).doSomething(); // userのupdateIdメソッドも呼ばれたことをテスト
}
}
Mockしたクラスで返す値をセットしておく
@ExtendWith(MockitoExtension.class)
public class IndexSelectScanTest {
@Mock
private User user; // mockしたいClass
@Test
public void testMock() {
when(user.getId()).thenReturn(10); // userのgetId()で10を返すようにセット
Example expl = new Example(user);
assertEquals(10, expl.getUserId()); // getUserId()内でuser.getId()を呼んでるとして10が返すことをテスト
}
}
Tips
when ~ thenReturn
コールされる順番で返す値を変える
when( method-call ).thenReturn( value1, value2, value3 );
verify
コールされる回数をテスト
import static org.mockito.Mockito.atLeast;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
verify(mockObject, atLeast(2)).someMethod("was called at least twice");
verify(mockObject, times(3)).someMethod("was called exactly three times");
verify(mockObject, never()).someMethod();
参考
- https://stackoverflow.com/questions/14889951/how-to-verify-a-method-is-called-two-times-with-mockito-verify
- https://stackoverflow.com/questions/8088179/using-mockito-with-multiple-calls-to-the-same-method-with-the-same-arguments
- https://www.javadoc.io/doc/org.mockito/mockito-core/2.7.21/org/mockito/Mockito.html#4