I have an activity that will grab a pojo from the extras, like so :
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Bundle extras = getIntent().getExtras();
if (extras != null)
{
MyPojo pojo = extras.getParcelable("pojo");
// do stuff with my pojo here
}
}
// button that shows a toast message
}
I’m having difficulty being able to test this using Robolectric, I believe I need to use a combination of ShadowIntents and ShadowActivities, but the documentation is a little thin, and any useful tutorials on this particular scenario are rather sparse.
This is what I’ve come up with so far :
@Test
public void assertClickingTagSightingDisplaysToast()
{
myActivity = new MyActivity();
myActivity.onCreate(null);
ShadowActivity shadowMyActivity = shadowOf(myActivity);
shadowMyActivity.setIntent(new Intent().putExtra("pojo", generateAPojo()));
ShadowButton shadowButton = (ShadowButton) shadowOf(shadowMyActivity.findViewById(R.id.myButton));
shadowButton.performClick();
assertThat(ShadowToast.getTextOfLatestToast(), equalTo("Button was clicked!"));
}
I keep getting a null pointer when I execute these tests, at the getIntent().getExtras() line of my activity, I’m assuming that my process of mocking the activities with intents is incorrect.
can anyone please help?
Thanks
I hit this very thing myself. It seems that you need to use the shadowActivity to manipulate the Intent, prior to calling your onCreate().
Seems like manipulating the activity itself should do the trick, but it doesn’t. Somebody way smarter than me will have to explain why this is — or someone only modestly smarter than me to tell you that the above is wrong.
— Quick note. Since Robolectric appears to be using javassist to manipulate the shadow classed, it’s important to do your class binding prior to the first load of a class. I followed their suggestion to do the binding in the Runner.