Can I do TDD for Android status bar notifications?
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开发者_Go百科 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?
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.
精彩评论