在Android应用程序中为Toasts编写JUnit测试

时间:2012-11-14 23:44:49

标签: java android unit-testing error-handling junit

我经常使用Toast.makeText().show()向我的Android应用的用户显示消息。这些可以是说明下一步做什么或错误消息。作为我的JUnit测试的一部分,我想包含这些消息在预期时出现的断言。我该怎么做呢?

2 个答案:

答案 0 :(得分:2)

我是通过使用 Robotium 框架来实现的,并在显示toast后立即调用它:

     TextView toastTextView = solo.getText(0);
     if(toastTextView != null){
         String toastText = toastTextView.getText().toString();
         assertEquals(toastText, "Your expected text here");
     }
     //wait for Toast to close
     solo.waitForDialogToClose(5000);

答案 1 :(得分:1)

由于最初提出这个问题,我发现以下解决方案对我有用:

public static void waitForToast(Solo solo, String message) {
    Assert.assertTrue(solo.waitForDialogToOpen(TIME_OUT));
    Assert.assertTrue(solo.searchText(message));
}