How to track activity while using Robolectric
I am new to Android and I am playing with Robolectric for my unit tests. I am facing the following problem.
I have an activity that I want to check.
MainActivity.java
public class MainActivity extends ActionBarActivity
implements NavigationDrawerFragment.NavigationDrawerCallbacks {
private NavigationDrawerFragment mNavigationDrawerFragment;
@Override
protected void onCreate (Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mNavigationDrawerFragment = (NavigationDrawerFragment)
getSupportFragmentManager().findFragmentById(R.id.navigation_drawer);
mNavigationDrawerFragment.setUp(
R.id.navigation_drawer,
(DrawerLayout) findViewById(R.id.drawer_layout));
}
@Override
public void onNavigationDrawerItemSelected (int position) {
...
}
}
This is the test class:
@RunWith(RobolectricGradleTestRunner.class)
@Config(constants = BuildConfig.class)
public class MainActivityTests {
private ActivityController<MainActivity> controller;
private MainActivity activity;
private MainActivity spy;
@Test
public void onCreate_shouldStartNavigationDrawerFragment () {
controller = Robolectric.buildActivity(MainActivity.class);
activity = controller.get();
assertThat(activity).isNotNull();
spy = spy(activity);
spy.onCreate(null);
verify(spy).onCreate(null);
}
}
But I am getting the following exception:
java.lang.IllegalStateException: System services not available to Activities before onCreate()
in line spy.onCreate(null)
.
I have been working for several hours and I have tried several workarounds (blindly) with no success. Can anyone visit me?
source to share
Here's what helped. I am using attach () before activating the activity. Tested with Robolectric 3.0
private MainActivity spyActivity;
@Before
public void setUp(){
MainActivity activity = Robolectric.buildActivity(MainActivity.class).attach().get();
spyActivity = spy(activity);
spyActivity.onCreate(null);
}
source to share
You must drive the lifecycle of your activity through Robolectric. See: http://robolectric.org/activity-lifecycle/
So, for your case, you can:
controller = Robolectric.buildActivity(MainActivity.class); activity = controller.get(); assertThat(activity).isNotNull(); spy = spy(activity); controller.create();
Note: It usually doesn't make sense to keep track of the activity lifecycle when testing with Robolectric, as you are managing it, so you only check that your own method calls are being executed.
source to share