我可以为Android状态栏通知做TDD吗?

时间:2011-08-30 05:28:33

标签: android tdd

为了对涉及Android状态栏的代码使用测试驱动的开发原则,我需要编写验证已达到预期状态的测试。例如,像下面这样的小单元测试将允许我验证我打算提出的通知实际显示:

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);
  }
}

正如示例所示,通知管理器本身似乎没有任何诊断方法,例如isShowing(id)get(id),我可以将其用于测试中的“验证”步骤。

我查看过优秀的Robotium工具包,但它们对于测试单个应用程序非常具体,所以它们不包括通知。

有人知道解决方案吗?

1 个答案:

答案 0 :(得分:3)

我通常不会测试第三方或系统api是否按预期工作。我会使用模拟NotificationManager并验证我的生产代码是否使用正确的参数调用notify真实 NotificationManager行为是否正常无法控制。

如果NotificationManager对模仿有抵抗力,你可以尝试将它包装在一个由你控制的瘦弱的类中。

我测试第三方或系统api的唯一时间是文档记录不佳,我需要确认其行为的猜测。一旦得到答案,这些测试通常会被丢弃。如果是这种情况,并且您发现很难使用测试框架进行测试,则可以始终创建一个简单的应用程序并直观地验证结果。