4

I'm having some troubles shadowing TimeZone.getDefault() using Robolectric since my AppTest.class is not using my static shadow mwthod in ShadowTimeZone.class.

AppTest.class

@RunWith(RobolectricTestRunner.class)
@Config(manifest = "../App/AndroidManifest.xml")
public class AppTest{

    @Test
    @Config(shadows = {ShadowTimeZone.class})
    public void testTimeZone() {    
        String expectedTimeZoneId = "Europe/London";

        TimeZone timeZone = TimeZone.getDefault();

        assertThat(timeZone.getID(), equalTo(expectedTimeZoneId));
    }
}

ShadowTimeZone.class

@Implements(TimeZone.class)
public class ShadowTimeZone {

    @Implementation
    public static TimeZone getDefault() {
        return TimeZone.getTimeZone("Europe/London");
    }
}
petruchio
  • 81
  • 4

2 Answers2

5

You don't need to use a shadow at all. Use TimeZone.setDefault(TimeZone.getTimeZone("Europe/London")) before your test or in a @Before setup method.

If you still want to use a shadow, the actual signature for getDefault is public static synchronized, so you may need to add synchronized to your shadow method to match.

malix
  • 3,566
  • 1
  • 31
  • 41
lopar
  • 2,432
  • 22
  • 14
0

By default you can only shadow classes from android package. But you can add more classes to work with shadows. See https://stackoverflow.com/a/29641926/3619179

Community
  • 1
  • 1
nenick
  • 7,340
  • 3
  • 31
  • 23