Mauricio Mauricio - 4 months ago 60
Android Question

Robolectric shadow not working

I'm trying to create a test with Robolectric. My goal is to be able to replace the functionality of one class (that comes for example from a library and I can't modify the code) from a custom behaviour.

I created this small test to simulate what I want to do:

@Config(shadows = {ShadowMessenger.class})
public class TestShadow {

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";

public static class ShadowMessenger extends OriginalMessenger {

public String getMessage() {
return "Shadow messenger";

In the example, OriginalMessenger is the class that is in the library and provides a default functionality. And ShadowMessenger is the class that contains the custom behaviour that I want to apply whenever I use OriginalMessenger.

However when I run the test it fails. The content of message is "Original messenger". As if the ShadowMessenger was never used.

What am I doing wrong?


Original you can only shadow android classes. But with a custom robolectric test runner you can also shadow your own classes.

Robolectric 3.1.4 (RobolectricGradleTestRunner was completely removed, so you need to override method described below in RobolectricTestRunner)

protected ShadowMap createShadowMap() {
    return new ShadowMap.Builder()
        .addShadowClass(OriginalMessenger.class, ShadowMessenger.class, true, true, true)

Robolectric 3.0

public InstrumentationConfiguration createClassLoaderConfig() {
    InstrumentationConfiguration.Builder builder = InstrumentationConfiguration.newBuilder();

Robolectric 2.4

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

example project