How to test for the appearance of a Toast message

I check, the following works:

if(someToast == null)
    someToast = Toast.makeText(this, "sdfdsf", Toast.LENGTH_LONG);
boolean isShown = someToast.getView().isShown();

Would anyone know how to test for the appearance of a Toast message on an Activity?

You can't -- sorry. By which, I mean there is no way to ask Android "hey, is a Toast showing? and what does it look like?".


Hm, actually there is a possibility to test the appearance of a toast. Simply create a subclass of Toast (e.g. MyOwnToast) and use this one in your program instead of Toast. In this subclass you can overwrite the show() method to notify you, that the Toast is being shown.

Additionally you can store the Toast within the show() method in kind of a ToastDatabase singleton from where you can access the Toast and it's view also after it has been shown and destroyed (haven't tested this with Toasts, but I often do that with the result intents of activities to keep them available for further tests after they have been destroyed - so it should be no problem to implement this with Toasts).

Beware: maybe you have to clone the Toast object or it's corresponding view for the ToastDatabase because probably it will be null after the Toast has been destroyed. Hope this helps!


We actually can now test for toast messages using robolectric. The example below is how our team is doing this for now:

    @Test
    public void ccButtonDisplaysToast() throws NullPointerException {
        Button ccRedButton = (Button) findViewById(R.id.cc_red);
        cc_red.performClick(); --> this calls the actual onClickListener implementation which has the toast.
        ShadowLooper.idleMainLooper(YOUR_TIME_HERE); --> This may help you.
        assertThat(ShadowToast.getTextOfLatestToast().toString(), equalTo("TEST_YOUR_TEXT_HERE"));
    }

Hope this helps