androidrobolectricrobolectric-gradle-plugin

Unable to create shadow classes with Robolectric 3


I followed the Robolectric documentation to create shadow classes but I'm not able to run shadow methods during test, it always uses original methods.

This is my code:

the Original class:

public class Original {
    public void print(){
        System.out.println("Hi from original class!");
    }
}

the Shadow class:

@Implements(Original.class)
public class ShadowOriginal {

    @Implementation
    public void print(){
        System.out.println("Hi from shadow class!");
    }
}

the test:

@RunWith(RobolectricGradleTestRunner.class)
@Config(manifest = "src/main/AndroidManifest.xml",
        emulateSdk = 21,
        reportSdk = 21,
        constants = BuildConfig.class,
        shadows = {ShadowOriginal.class})
public class OasisTests {
    @Test
    public void test() {
        Original t = new Original();
        t.print();
    }
}

When I run the tests, it always display "Hi from original class!"

What is wrong in my code? I uses

How can I solve this issue?

Thanks in advance


Solution

  • You need a custom robolectric runner where you can register own classes so they can be shadowed. See Robolectric shadow not working