11

私は簡単なテストケースを持っています:

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

TableElementは、メソッドがinsertRow次のように定義されたGWTクラスです。

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でそのようなメソッドをモックする方法または回避策はありますか?

4

2 に答える 2

12

このGoogleグループのスレッドによると、Mockito自体はネイティブメソッドをモックできないようです。ただし、2つのオプションがあります。

  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を使用すると、ネイティブメソッドをモックするために呼び出されるMockitoAPI拡張機能が使用されます。PowerMockito欠点は、テストプロジェクトにロードする別の依存関係があることです(これは、使用するためにサードパーティのライブラリを最初に監査する必要がある一部の組織では問題になる可能性があることを認識しています)。

個人的にはオプション2を使用します。これは、GWTプロジェクトが独自のクラスをインターフェイスでラップする可能性が低く(モックする必要のあるネイティブメソッドが多い可能性が高いため)、ネイティブメソッドのみをラップするために自分で行うためです。電話はあなたの時間の無駄です。

于 2012-04-19T07:51:38.500 に答える
0

他の誰かがこれについてつまずいた場合:その間に(2013年5月に)GwtMockitoが現れ、PowerMockのオーバーヘッドなしでこの問題を解決します。

これを試して

@RunWith(GwtMockitoTestRunner.class)
public class MyTest {

    @Test
    public void test() throws Exception{
        TableElement table = mock(TableElement.class);
        table.insertRow(0);
    }
}
于 2016-08-08T15:35:45.647 に答える