Mock native method with a Robolectric Custom shadow class

假装没事ソ 提交于 2019-12-24 12:04:04

问题


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();

}

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 { ... }

}

Here is my test:

@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);
  }

}

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.


回答1:


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

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());
    }
}
}



回答2:


For robolectric 3.+ :

Create a custom test runner that extends RobolectricGradleTestRunner:

public class CustomRobolectricTestRunner extends RobolectricGradleTestRunner {  
    public CustomRobolectricTestRunner(Class<?> klass) throws InitializationError {
        super(klass);
    }

    public InstrumentationConfiguration createClassLoaderConfig() {
        InstrumentationConfiguration.Builder builder = InstrumentationConfiguration.newBuilder();
        builder.addInstrumentedPackage("com.yourClassPackage");
        return builder.build();
    }
}


来源:https://stackoverflow.com/questions/28181870/mock-native-method-with-a-robolectric-custom-shadow-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!