简体   繁体   English

使用Mockito的Android小部件中的存根方法

[英]Stub methods in Android widget using Mockito

I want to stub some methods in a custom Android Widget to test it. 我想在自定义Android窗口小部件中存根一些方法进行测试。 I made a test case: 我做了一个测试案例:

public class FooWidgetTest extends AndroidTestCase {
    @Override
    protected void setUp() throws Exception {
        super.setUp();
        System.setProperty("dexmaker.dexcache", getContext().getCacheDir().getPath());
    }

    public void testMeasure() {
        final FooWidget widget = spy(new FooWidget(getContext()));
        //doReturn(42).when(widget).getFoo();
        widget.measure(makeMeasureSpec(100, EXACTLY), makeMeasureSpec(80, AT_MOST));
        assertEquals(100, widget.getMeasuredWidth());
        assertEquals(80, widget.getMeasuredHeight());
    }
}

Here I create a spy using Mockito and call measure to test the implementation of onMeasure . 在这里,我使用Mockito创建一个间谍并调用measure来测试onMeasure的实现。 When measure is called I receive the following error: 调用measure会收到以下错误:

java.lang.IllegalAccessError: tried to access method com.foo.widget.FooWidget.isLayoutModeOptical:()Z from class FooWidget_Proxy

The method isLayoutModeOptical from ViewGroup has package-level visibility therefore Mockito couldn't call it from the proxy object. ViewGroup isLayoutModeOptical方法具有包级可见性,因此Mockito无法从代理对象调用它。

Is there any way to solve this error? 有什么办法可以解决这个错误?

You could try to add: 您可以尝试添加:

    doReturn(true).when(widget).isLayoutModeOptical();

Mockito should be able to mock package level methods also :) Mockito也应该能够模拟包级方法:)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM