簡體   English   中英

Mockito - 使用本機方法模擬類

[英]Mockito - mocking classes with native methods

我有簡單的測試用例:

@Test
public void test() throws Exception{
       TableElement table = mock(TableElement.class);
       table.insertRow(0);
}

其中TableElement是GWT類,方法insertRow定義為:

public final native TableRowElement insertRow(int index);

當我開始測試時,我得到:

java.lang.UnsatisfiedLinkError: com.google.gwt.dom.client.TableElement.insertRow(I)Lcom/google/gwt/dom/client/TableRowElement;
    at com.google.gwt.dom.client.TableElement.insertRow(Native Method)

我相信哪個與insertRow方法有關。 有沒有辦法或解決方法來模擬Mockito的這些方法?

Mockito本身似乎無法根據此Google Group線程模擬本機方法。 但是,您有兩個選擇:

  1. TableElement類包裝在一個接口中並模擬該接口以正確測試您的SUT調用包裝的insertRow(...)方法。 缺點是您需要添加額外的接口(當GWT項目應該在他們自己的API中完成此操作時)以及使用它的開銷。 接口的代碼和具體實現如下所示:

     // the mockable interface public interface ITableElementWrapper { public void insertRow(int index); } // the concrete implementation that you'll be using public class TableElementWrapper implements ITableElementWrapper { TableElement wrapped; public TableElementWrapper(TableElement te) { this.wrapped = te; } public void insertRow(int index) { wrapped.insertRow(index); } } // the factory that your SUT should be injected with and be // using to wrap the table element with public interface IGwtWrapperFactory { public ITableElementWrapper wrap(TableElement te); } public class GwtWrapperFactory implements IGwtWrapperFactory { public ITableElementWrapper wrap(TableElement te) { return new TableElementWrapper(te); } } 
  2. 使用Powermock和它的名為PowerMockitoMockito API擴展來模擬本機方法。 缺點是您有另一個依賴項加載到您的測試項目(我知道這可能是一些組織的問題,其中第三方庫必須首先被審計才能被使用)。

我個人會選擇2,因為GWT項目不可能在接口中包裝自己的類(並且它更可能有更多需要模擬的本機方法)並且自己做它只包裝本機方法打電話只是浪費你的時間。

萬一其他人偶然發現:在此期間( 20135月GwtMockito出現了,這解決了這個問題,沒有PowerMock的開銷。

試試這個

@RunWith(GwtMockitoTestRunner.class)
public class MyTest {

    @Test
    public void test() throws Exception{
        TableElement table = mock(TableElement.class);
        table.insertRow(0);
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM