Mock native方法与Robolectric自定义shadow类 [英] Mock native method with a Robolectric Custom shadow class

查看:1199
本文介绍了Mock native方法与Robolectric自定义shadow类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个类,有一个常规的方法和一个本地方法,我想嘲笑:

I have a class with a regular method and a native method that I'd like to mock:

public class MyClass {

  public int regularMethod() { ... }
  public void native myNativeMethod();

}



我使用Robolectric测试我的应用程式,试图找出一种方法来使用自定义阴影类来模拟这些方法。这是我的影子类:

I am using Robolectric to test my app, and I am trying to figure out a way to mock these methods using a custom shadow class. Here is my shadow class:

@Implements(MyClass.class)
public class MyShadowClass {

  @Implementation
  public int regularMethod { return 0; }

  @Implementation
  public void nativeMethod { ... }

}

这是我的测试:

@RunWith(RobolectricTestRunner.class)
@Config(manifest = Config.NONE)
public class MyTest {

  @Test
  @Config(shadows = { MyShadowClass.class })
  public void test() {
    MyClass obj = new MyClass();
    Assert.assertEquals(obj.regularMethod(), 0);
  }

}

。嘲笑本地方法可能是一个与Shadow类的延伸,但我认为使用自定义shadow类这样会导致shadow类代码被调用。

This is not working as I thought. Mocking the native method might be a stretch with the Shadow class, but I thought that using a custom shadow class in this way would cause the shadow class code to get called.

推荐答案

我猜robolectric不知道你的类应该被遮蔽;)

I guess robolectric does not know that your class should be shadowed ;)

这里是如何告诉robolectric不是android sdk类。<​​/ p>

Here is how to tell robolectric that you will shadow some not android sdk classes.

public class MyRobolectricTestRunner extends RobolectricTestRunner {

@Override
protected ClassLoader createRobolectricClassLoader(Setup setup, SdkConfig sdkConfig) {
    return super.createRobolectricClassLoader(new ExtraShadows(setup), sdkConfig);
}

class ExtraShadows extends Setup {
    private Setup setup;

    public ExtraShadows(Setup setup) {
        this.setup = setup;
    }

    public boolean shouldInstrument(ClassInfo classInfo) {
        boolean shouldInstrument = setup.shouldInstrument(classInfo);
        return shouldInstrument
                || classInfo.getName().equals(MyClass.class.getName());
    }
}
}

这篇关于Mock native方法与Robolectric自定义shadow类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆