1 package org.robolectric; 2 3 import static org.junit.Assert.assertEquals; 4 import static org.junit.Assert.assertFalse; 5 import static org.junit.Assert.assertTrue; 6 7 import org.junit.Test; 8 import org.junit.runner.RunWith; 9 import org.robolectric.annotation.Implementation; 10 import org.robolectric.annotation.Implements; 11 import org.robolectric.annotation.internal.Instrument; 12 import org.robolectric.internal.SandboxTestRunner; 13 import org.robolectric.internal.bytecode.RobolectricInternals; 14 import org.robolectric.internal.bytecode.SandboxConfig; 15 16 @RunWith(SandboxTestRunner.class) 17 public class StaticInitializerTest { 18 @Test whenClassIsUnshadowed_shouldPerformStaticInitialization()19 public void whenClassIsUnshadowed_shouldPerformStaticInitialization() throws Exception { 20 assertEquals("Floyd", ClassWithStaticInitializerA.name); 21 } 22 23 @Instrument 24 public static class ClassWithStaticInitializerA { 25 static String name = "Floyd"; 26 } 27 28 29 @Test 30 @SandboxConfig(shadows = {ShadowClassWithoutStaticInitializerOverride.class}) whenClassHasShadowWithoutOverrideMethod_shouldPerformStaticInitialization()31 public void whenClassHasShadowWithoutOverrideMethod_shouldPerformStaticInitialization() throws Exception { 32 assertEquals("Floyd", ClassWithStaticInitializerB.name); 33 34 RobolectricInternals.performStaticInitialization(ClassWithStaticInitializerB.class); 35 assertEquals("Floyd", ClassWithStaticInitializerB.name); 36 } 37 38 @Instrument public static class ClassWithStaticInitializerB { 39 public static String name = "Floyd"; 40 } 41 42 @Implements(ClassWithStaticInitializerB.class) public static class ShadowClassWithoutStaticInitializerOverride { 43 } 44 45 @Test 46 @SandboxConfig(shadows = {ShadowClassWithStaticInitializerOverride.class}) whenClassHasShadowWithOverrideMethod_shouldDeferStaticInitialization()47 public void whenClassHasShadowWithOverrideMethod_shouldDeferStaticInitialization() throws Exception { 48 assertFalse(ShadowClassWithStaticInitializerOverride.initialized); 49 assertEquals(null, ClassWithStaticInitializerC.name); 50 assertTrue(ShadowClassWithStaticInitializerOverride.initialized); 51 52 RobolectricInternals.performStaticInitialization(ClassWithStaticInitializerC.class); 53 assertEquals("Floyd", ClassWithStaticInitializerC.name); 54 } 55 56 @Instrument public static class ClassWithStaticInitializerC { 57 public static String name = "Floyd"; 58 } 59 60 @Implements(ClassWithStaticInitializerC.class) 61 public static class ShadowClassWithStaticInitializerOverride { 62 public static boolean initialized = false; 63 64 @Implementation __staticInitializer__()65 protected static void __staticInitializer__() { 66 initialized = true; 67 } 68 } 69 } 70