Java – robolectric shadow does not work
I tried to create a test with robolectric My goal is to be able to replace the functionality of a class from custom behavior (for example, from a library without modifying the code)
I created this little test to simulate what I want to do:
@RunWith(RobolectricTestRunner.class)
@Config(shadows = {ShadowMessenger.class})
public class TestShadow {
@Test
public void testMessenger() {
OriginalMessenger messenger = new OriginalMessenger();
String message = messenger.getMessage();
Assert.assertEquals("Shadow messenger",message);
}
public static class OriginalMessenger {
public String getMessage() {
return "Original messenger";
}
}
@Implements(OriginalMessenger.class)
public static class ShadowMessenger extends OriginalMessenger {
@Implementation
public String getMessage() {
return "Shadow messenger";
}
}
}
In this example, originalmessanger is a class in the library and provides default functionality Shadowmessenger is a class that contains custom behavior to apply when I use original messenger
But when I failed to run the test The content of the message is "original messenger" It seems that shadowmessenger has never been used
What on earth did I do wrong?
Solution
So you can only shadow Android classes However, you can also influence your course by testing runners with a customized robolectric
Robolectric 3.1. 4 (robolectricgradletestrunner has been completely deleted, so you need to override the method described in robolectrictestrunner)
@Override
protected ShadowMap createShadowMap() {
return new ShadowMap.Builder()
.addShadowClass(OriginalMessenger.class,ShadowMessenger.class,true,true)
.build();
}
Robolectric 3.0
@Override
public InstrumentationConfiguration createClassLoaderConfig() {
InstrumentationConfiguration.Builder builder = InstrumentationConfiguration.newBuilder();
builder.addInstrumentedClass(OriginalMessenger.class.getName());
return builder.build();
}
Robolectric 2.4
@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 shoudInstrument = setup.shouldInstrument(classInfo);
return shoudInstrument
|| classInfo.getName().equals(OriginalMessenger.class.getName());
}
}
Sample project https://github.com/nenick/android-gradle-template/
