Mockito - 使用本机方法模拟类

时间:2012-04-19 07:45:15

标签: java gwt mockito 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模拟这样的方法吗?

2 个答案:

答案 0 :(得分: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和名为PowerMockito的{​​{3}}来模拟本机方法。缺点是你有另一个依赖加载到你的测试项目(我知道这可能是一些组织的问题,其中第三方库必须首先被审计才能被使用)。
  3. 就我个人而言,我选择2,因为GWT项目不太可能在接口中包装自己的类(并且更有可能他们有更多需要模拟的本机方法)并且只为自己做包装本地方法调用只是浪费你的时间。

答案 1 :(得分:0)

如果其他人偶然发现这一点:在此期间(May 2013GwtMockito出现,这解决了这个问题,而没有PowerMock的开销。

试试这个

@RunWith(GwtMockitoTestRunner.class)
public class MyTest {

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