MockitoでサクサクTest Double生活(下)

書いた人
大中浩行(せとあずさ♂)(@setoazusa)

MockitoでサクサクTest Double生活(下)


MockitoMockitoSpy7RC1Mockito1.9.0

 




times使


1verify2times(1)1times(1)


verify(response, times(1)).sendRedirect("/top.jsp");


verify(response).sendRedirect("/top.jsp");


 Spy


MockitoSpy

Spyspy使Mockfinal


when(list.add("value")).thenReturn(true);

使Spy
List<String> list = new ArrayList<String>();
list = spy(list);
//IndxOutOfBoundsExceptionになる
when(list.get(0)).thenReturn("value");

doReturndoThrow使
List<String> list = new ArrayList<String>();
list = spy(list);
// これは大丈夫
doReturn("value").when(list).get(0);
assertThat(list.get(0), is("value"));

Spy使

 Mockito1.9

 Spy


Mockito@Mock

Mockito1.9.0@Spy@SpySpy
//MockitoJUnitRunnerを指定する
@RunWith(MockitoJUnitRunner.class)
public class NewFeatureTest {
       /**
        * Spyを生成する
        */
       @Spy
       List<String> list = new ArrayList<String>();
       /**
        * Mockを生成する
        */
       @Mock
       List<String> mockList

 




whenmockgetMock
@Test
public void ワンライナーによるモック生成() throws Exception {
    HttpServletRequest request = when(mock(HttpServletRequest.class).getParameter("param")).thenReturn("value").getMock();
    assertThat(request.getParameter("param"), is("value"));
}

 


1verifyNoMoreInteractions使

Mockito1.9.0ignoreStubs使
 @Test
 public void ignoreStubによる検証の除外() throws Exception {
  List<Integer> mock1 = mock(List.class);

  //スタブの適用
  when(mock1.get(0)).thenReturn(10);

  //スタブメソッドの呼び出しもインタラクションに含まれる
  mock1.get(0);

  mock1.clear();

  verify(mock1).clear();

  try{
   verifyNoMoreInteractions(mock1);
   fail();
  } catch(NoInteractionsWanted ignore){
   //検証時に例外になっていた
  }
  //こちらは例外にならない
  verifyNoMoreInteractions(ignoreStubs(mock1));

 }

SUT(System Under Test) ()

 


MockitoMockitoAPI
Last modified:2011/11/30 22:35:20
Keyword(s):
References:[xUTP Magazine 0002号] [ぺけま]

*1 テストケースがテスト対象とするコンポーネント