0
0

More than 1 year has passed since last update.

mockito基本

Last updated at Posted at 2023-01-08

基本

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();

参考

  1. https://stackoverflow.com/questions/14889951/how-to-verify-a-method-is-called-two-times-with-mockito-verify
  2. https://stackoverflow.com/questions/8088179/using-mockito-with-multiple-calls-to-the-same-method-with-the-same-arguments
  3. https://www.javadoc.io/doc/org.mockito/mockito-core/2.7.21/org/mockito/Mockito.html#4
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0