Mock native method with a Robolectric Custom shado

2019-08-10 13:10发布

问题:

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