單元測試mockito

jopen 9年前發布 | 13K 次閱讀 單元測試 Mockito

參考了http://qiuguo0205.iteye.com/blog/1456528 的博客,謝謝!

1、驗證動作,我調用了哪些方法。

        List<String>  mockedList = mock(List.class);

        mockedList.add("one");

        verify(mockedList).add("one");

      相反的,還有沒有調用哪些方法

        verify(mockedList,never()).add("one");

2、模擬一個接口,正常實現一個接口很麻煩的,但使用mockito,可以輕易實現

        List mockedList = mock(List.class);

        when(mockedList.get(0)).thenReturn("first");

        System.out.println(mockedList.get(0));

      如果你說我多次調用,返回不一樣的值

      when(mockedList.get(1)).thenReturn("two").thenReturn("two1");

    System.out.println(mockedList.get(1));

    System.out.println(mockedList.get(1));      

    這個功能設計的,我無法形容,可以想想一個程序員被需求逼到什么程度。太佩服這哥們的腦子了!

3、驗證各種動作

    

   List<String> mockedList = mock(List.class);

        // using mock

        mockedList.add("once");


        mockedList.add("twice");

        mockedList.add("twice");


        mockedList.add("three times");

        mockedList.add("three times");

        mockedList.add("three times");


        mockedList.add("five times");

        mockedList.add("five times");

       verify(mockedList).add("once");//驗證.add("once")動作

       verify(mockedList, times(1)).add("once");//驗證.add("once")動作發生一次。

        verify(mockedList, times(2)).add("twice");//兩次

        verify(mockedList, times(3)).add("three times");//三此

        verify(mockedList, never()).add("never happened");   //從來沒干過

        verify(mockedList, atLeastOnce()).add("three times");//最少一次

        verify(mockedList, atLeast(2)).add("five times");//最少兩次

        verify(mockedList, atMost(5)).add("three times");//最多5次

4、偽造值

        List list = new LinkedList();

        List spy = spy(list);

        when(spy.size()).thenReturn(100);

        System.out.println(spy.get(0));

5、偽造動作 

          List mockedList =  mock(LinkedList.class ) ;

        doThrow(new RuntimeException()).when(mockedList).clear(); //當調用clear()時,拋個異常

        mockedList.clear();

 本文由用戶 jopen 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!