0

In order to use test-driven development principles for code involving the Android status bar, I would need to write tests that verify an expected state has been achieved. For example, a little unit test like the following would allow me to verify that the notification I intended to put up is actually showing:

public class NotificationTest extends AndroidTestCase {

  public void testCanNotify() {
    // setup SUT
    NotificationManager mgr = (NotificationManager) getContext().getSystemService(
            Context.NOTIFICATION_SERVICE);
    Notification notif = new Notification(android.R.drawable.stat_notify_error, "ticker", 0);
    PendingIntent intent = PendingIntent.getActivity(getContext(), 0, null, 0);
    notif.setLatestEventInfo(getContext().getApplicationContext(), "title", "text", intent);
    int id = 123;

    // exercise SUT
    mgr.notify(id, notif);

    // verify result
    // QUESTION: HERE I WOULD LIKE TO SAY:
    // assertTrue(mgr.isShowing(id));

    // teardown
    mgr.cancel(id);
  }
}

So as the example shows, the notification manager itself does not seem to have any diagnostic methods such as isShowing(id) or get(id) which I could use for the "verify" step in the test.

I have looked at the excellent Robotium toolkit, but they are very specific about testing a single application, so they don't cover notifications.

Does anyone know a solution?

marc1s
  • 1,981
  • 1
  • 13
  • 13

1 Answers1

3

I wouldn't normally test whether a third party or system api works as expected. I would use a mock NotificationManager and verify whether my production code calls notify with the correct parameters. Whether the real NotificationManager behaves properly isn't really something you control.

If NotificationManager is resistant to mocking you can try wrapping it in a thin class that's under your control.

The only time I test a third party or system api is when it is poorly documented and I need to confirm a guess about its behavior. These kind of tests are usually thrown away once I have my answer. If this is the case and you are finding it difficult to test using a test framework you can always create a simple application and visually verify the results.

Kenneth Cochran
  • 11,954
  • 3
  • 52
  • 117
  • Thanks, that makes sense to me. In fact, the intention was not to test the notification manager, but rather cross-dependencies between my own various activities. I see your point that this would best be done in a mock context -- I'll look into this. – marc1s Sep 08 '11 at 11:22