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:
@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 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?
See Question&Answers more detail:os