Sky's blog

          我和我追逐的夢(mèng)

          常用鏈接

          統(tǒng)計(jì)

          其他鏈接

          友情鏈接

          最新評(píng)論

          easymock教程-使用MockControl

               在easymock中,通常我們使用一下的代碼來創(chuàng)建mock對(duì)象

              IMyInterface mock = createStrictMock(IMyInterface.class);
              replay(mock);
              verify(mock); 
              reset(mock);

              如果需要mock多個(gè)對(duì)象,則需要如此:

              IMyInterface1 mock1 = createStrictMock(IMyInterface1.class);
              IMyInterface2 mock2 
          = createStrictMock(IMyInterface2.class);
              IMyInterface3 mock3 
          = createStrictMock(IMyInterface2.class);
              ...
              replay(mock1, mock2, mock3, ...);
              verify(mock1, mock2, mock3, ...); 
              reset(mock1, mock2, mock3, ...);

              不僅需要為每個(gè)mock對(duì)象增加create語句,而且需要為這個(gè)新增的mock對(duì)象更新replay()/verify()/reset()方法,比較啰嗦,而且容易出錯(cuò)。

              這種情況下可以考慮使用MocksControl來簡化代碼:

              IMocksControl mocksControl = createControl();
              IMyInterface1 mock1 
          = mocksControl.createMock(IMyInterface1.class);
              IMyInterface2 mock2 
          = mocksControl.createMock(IMyInterface2.class);
              IMyInterface3 mock3 
          = mocksControl.createMock(IMyInterface3.class);
              ...
              mocksControl.replay();
              mocksControl.verify(); 
              mocksControl.reset();


              IMocksControl接口容許創(chuàng)建多個(gè)mock對(duì)象,這些創(chuàng)建的對(duì)象自動(dòng)關(guān)聯(lián)到這個(gè)mocksControl實(shí)例上,以后再調(diào)用replay()/verify()/reset()時(shí)就不需要逐個(gè)列舉出每個(gè)mock對(duì)象。當(dāng)mock對(duì)象比較多,尤其是原有代碼上新增mock 對(duì)象時(shí)非常方便。

              事實(shí)上,Easymock.createMock()方法內(nèi)部實(shí)現(xiàn)也是使用IMocksControl的:

              public static <T> T createMock(final Class<T> toMock) {
                  
          return createControl().createMock(toMock);
              }


              
          public static IMocksControl createControl() {
                  
          return new MocksControl(MocksControl.MockType.DEFAULT);
              }

               除了使用方便外,使用IMocksControl還有另外一個(gè)重要的好處,就是如果使用strict control,則可以跨多個(gè)mock對(duì)象檢測(cè)方法的調(diào)用順序,具體的內(nèi)容請(qǐng)參考本教程中的"strict和nice"一文。

          posted on 2010-10-26 17:18 sky ao 閱讀(2617) 評(píng)論(0)  編輯  收藏 所屬分類: software test

          主站蜘蛛池模板: 兴仁县| 常州市| 赤壁市| 铁岭市| 福贡县| 同江市| 佛山市| 丽江市| 勃利县| 微山县| 千阳县| 河东区| 永春县| 五华县| 策勒县| 怀宁县| 盘山县| 东海县| 高淳县| 开化县| 永新县| 呼和浩特市| 彭阳县| 明星| 康保县| 永昌县| 自贡市| 汝城县| 宜春市| 连山| 永靖县| 丹巴县| 乐清市| 辛集市| 天门市| 游戏| 林西县| 霍城县| 璧山县| 安新县| 射阳县|