2

I often use Toast.makeText().show() to display messages to the user of my Android app. These can be instructions what to do next or error messages. As part of my JUnit tests, I would like to include assertions that these messages appear when expected. How do I go about doing this?

Code-Apprentice
  • 81,660
  • 23
  • 145
  • 268
  • 1
    I can't answer your question but I have to comment about using `Toast` for instructions or reporting error messages. A `Toast` is meant to be short-lived and it's easy for a user to miss this type of message. In other words, don't use `Toast` for anything which is crucial to the UX - display a dialog or a notification instead....something permanent in case the user is distracted and doesn't see your `Toast` messages. – Squonk Nov 15 '12 at 00:39
  • @Squonk That's a good point. I will certainly consider changing my UI to use something other than `Toast`s. I suspect I will encounter similar issues when trying to write tests. – Code-Apprentice Nov 15 '12 at 00:40
  • Related: http://stackoverflow.com/questions/2405080/how-to-test-for-the-appearance-of-a-toast-message – Andrew T. Sep 02 '15 at 08:50

2 Answers2

2

I do it by using Robotium framework, and calling this immediately after the toast is shown:

     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);
Uriel Frankel
  • 14,304
  • 8
  • 47
  • 69
  • Robotium is on my long list of technologies to learn. Thanks for the answer to my question and reminding me to download and take a look at this testing framework. – Code-Apprentice May 21 '13 at 00:24
1

Since originally asking this question, I have found the following solution which works well for me:

public static void waitForToast(Solo solo, String message) {
    Assert.assertTrue(solo.waitForDialogToOpen(TIME_OUT));
    Assert.assertTrue(solo.searchText(message));
}
Code-Apprentice
  • 81,660
  • 23
  • 145
  • 268