title: Unit testing Activity.startService() call?
body: <p>Attempting to write my first Android-by-TDD app (I've written a few small Android apps without TDD, so am familiar with the environment), but I can't seem to get my head around how to write my first test.</p>
  
  <p>The scenario:</p>
  
  <p>I have an activity, TasksActivity, and a service, TasksService.  I need to test that TasksActivity starts TasksService in its onStart() method.</p>
  
  <p>The test I've written is this:</p>
  
  <pre><code>public class ServiceControlTest extends ActivityUnitTestCase&lt;TasksActivity&gt;{
  public ServiceControlTest() {
      super(TasksActivity.class);
  }
  
  public void testStartServiceOnInit () {
      final AtomicBoolean serviceStarted = new AtomicBoolean(false);
      setActivityContext(new MockContext() {
          @Override
          public ComponentName startService(Intent service) {
              Log.v("mockcontext", "Start service: " + service.toUri(0));
              if (service.getComponent().getClassName().equals (TasksService.class.getName()))
                  serviceStarted.set(true);
              return service.getComponent();
          }
      });
      startActivity(new Intent(), null, null);
      assertTrue ("Service should have been started", serviceStarted.get());
  }           
  }
  </code></pre>
  
  <p>In my onCreate() method in TasksActivity I have:</p>
  
  <pre><code>    startService(new Intent(this, TasksService.class));
  </code></pre>
  
  <p>I have also tried</p>
  
  <pre><code>    getBaseContext().startService(new Intent(this, TasksService.class));
  </code></pre>
  
  <p>But in neither case does my MockContext's startService method get called.  Is there a way I can set up interception of this method?  I'd really rather not have to start wrapping the basic Android APIs in order to perform such basic tests...</p>