2012-04-19 134 views
9

我有簡單的測試案例:當我啓動測試我得到的Mockito - 嘲諷類與本地方法

public final native TableRowElement insertRow(int index); 

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

哪裏TableElement是GWT類方法insertRow定義爲:

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的這種方法?

回答

11

Mockito本身似乎不能嘲笑根據這個Google Group thread本地方法。然而,你有兩個選擇:

  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和它的Mockito API extensionPowerMockito嘲笑本地方法。缺點是你有另一個依賴加載到你的測試項目中(我知道這可能是一些組織的問題,第三方庫必須先審覈才能使用)。

個人而言,我會去與選項2去,如GWT項目不太可能在包裹界面自己的類(和它更有可能他們有更多的本地方法需要被嘲笑),並做自己只打包本地方法調用只是浪費你的時間。

+0

不幸的是我有超過'TableElement'類無法控制 - 它屬於外部庫。然而,Powermock Mockito API擴展看起來非常有趣,我會檢查出來。 – 2012-04-19 07:56:14

+0

當你包裝別人的東西,然後**你**有控制權。 :-)這是包裝,[適配器](http://en.wikipedia.org/wiki/Adapter_pattern)或[façades](http://en.wikipedia.org/wiki/Facade_pattern)的美妙之處。 – Spoike 2012-04-19 08:23:36

+0

非常感謝您的詳細解答。包裝將起作用,我可能會使用它作爲最後的手段,但對我的口味來說,它太多傾斜和複雜的生產代碼只用於測試目的:(。 – 2012-04-19 08:30:22

0

如果有其他人絆倒這個:在此期間(在May 2013GwtMockito出現了,它解決了這個問題,沒有PowerMock的開銷。

試試這個

@RunWith(GwtMockitoTestRunner.class) 
public class MyTest { 

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