title: How to spy on Activity when using Robolectric
body: <p>I am new on Android and I am playing around with Robolectric for my unit tests.
  I am facing the following problem.</p>
  
  <p>I have an activity I want to test.</p>
  
  <p>MainActivity.java</p>
  
  <pre><code>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) {
          ...
      }
  }
  </code></pre>
  
  <p>This is the test class:</p>
  
  <pre><code>@RunWith(RobolectricGradleTestRunner.class)
  @Config(constants = BuildConfig.class)
  public class MainActivityTests {
  
      private ActivityController&lt;MainActivity&gt; 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);
      }
  }
  </code></pre>
  
  <p>But I am getting the following exception: </p>
  
  <p><code>java.lang.IllegalStateException: System services not available to Activities before onCreate()</code> at line <code>spy.onCreate(null)</code>.</p>
  
  <p>I have been googling for hours and I have tried several workarounds (blindly) without any success. May please anyone guide me?</p>