Shadowing static fields

610 views
Skip to first unread message

Detrie

unread,
Dec 4, 2015, 8:17:33 AM12/4/15
to Robolectric
Hi All,

Is it possible to shadow static fields. I would like to create a shadow of android.os.Build but I can't seem to make it work. This is what I tried

@Implements(Build.class)
public class ShadowBuild {

public static final String CPU_ABI = "poo";
public static final String CPU_ABI2 = "poo2";

@RealObject
private Build mBuild;
}

And then

@RunWith(RobolectricTestRunner.class)
@Config(manifest = TestConstants.MANIFEST_LOCATION,
        sdk
= Build.VERSION_CODES.JELLY_BEAN_MR1,
        shadows
= ShadowBuild.class)
public class TestClass {


   
@Before
    public void setUp() throws IOException {
       
System.out.println(Build.CPU_ABI);
       
System.out.println(Build.CPU_ABI2);
}

Michael Grafton

unread,
Dec 5, 2015, 2:56:26 PM12/5/15
to robol...@googlegroups.com
I don't know if this is possible or not - Robolectric has a lot of reflection tools at it's disposal and it certainly knows how to re-write static final fields.

That being said, it is probably less hassle to simply wrap these config values in an Object that you can mock out easily during tests.

Mike

--
You received this message because you are subscribed to the Google Groups "Robolectric" group.
To unsubscribe from this group and stop receiving emails from it, send an email to robolectric...@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Tyler Schultz

unread,
Dec 5, 2015, 3:55:50 PM12/5/15
to robol...@googlegroups.com

Christian Williams

unread,
Dec 7, 2015, 5:42:14 AM12/7/15
to robol...@googlegroups.com
The problem here is that javac is allowed to inline any final primitive fields at compile time, so you likely won't have the opportunity to change it at runtime. Possibly more likely to work if you don't pass -O to javac?

(Hey Tyler and Mike!)

--X [typos courtesy of my iPhone]

Michael Grafton

unread,
Dec 7, 2015, 10:51:47 AM12/7/15
to robol...@googlegroups.com
Wow, it's like olden times!

Aaron Simmons

unread,
Mar 26, 2016, 3:54:29 PM3/26/16
to Robolectric
While I don't think you can override the static fields in Build, you can modify at where it gets is values-- these come from SystemProperties.  Robolectric has a ShadowSystemProperties (see here).

Joe Bowbeer

unread,
Oct 11, 2016, 4:40:38 AM10/11/16
to Robolectric
Something like the following works for me:

@Config(shadows=AmazonSystemProperties.class)
@Test
public void testMyDeviceMadeByAmazon() {
assertTrue("Amazon".equals(android.os.Build.MANUFACTURER));
}

@Implements(className = "android.os.SystemProperties")
public static class AmazonSystemProperties extends ShadowSystemProperties {

@Implementation
@SuppressWarnings("unused")
public static String get(String key, String def) {
if ("ro.product.manufacturer".equals(key)) {
return "Amazon";
}
return ShadowSystemProperties.get(key, def);
}
}
Reply all
Reply to author
Forward
0 new messages