Mock custom method with Robolectric Custom shadow class

I have a class with a regular method and my own method that I would like to make fun of:

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

I use Robolectric to test my application, and I am trying to find 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 does not work as I thought. Mocking your own method can be extended with the Shadow class, but I thought that using a custom shadow class this way would cause the shadow class code to be called.

+1
class mocking shadow robolectric
source share
2 answers

I think robolectric does not know that your class should be obscured;)

Here's how to tell robolectric that you will hide some 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
source share

For robolectric 3. +:

Create your own 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(); } } 
0
source share

All Articles