3

I am writing a test to check if a custom Toast is being shown. The Toast is not being constructed and shown in an Activity instance. I have a created a class that has access to the Context.

public class ToastHandler{
    private Context context;
    public ToastHander(Context context){
       this.context = context;
    }

   public createToast(DataStructure data){
      // Create and show Custom Toast using data and context
   }
}

How should I go about testing this? I am using Espresso.

LonsomeHell
  • 573
  • 1
  • 7
  • 29
  • 1
    Does this answer your question? [Checking toast message in android espresso](https://stackoverflow.com/questions/28390574/checking-toast-message-in-android-espresso) – justarandomuser12345 Dec 13 '19 at 18:36

1 Answers1

1

What about

onView(withText(R.string.toast_text)).inRoot(withDecorView(not(mActivityRule.getActivity().getWindow().getDecorView()))).check(matches(isDisplayed()));

?

If there is such need you can create matcher like this

http://baroqueworksdev.blogspot.de/2015/03/how-to-check-toast-window-on-android.html

Arek Wrzos
  • 11
  • 1
  • How to get `mActivityRule`. I don't need to start an Activity I want to test the `Toast`being shown only. – LonsomeHell Apr 05 '18 at 08:23
  • Espresso is for view (UI) testing, if you are trying to test toast without views maybe its not the case for you to use espresso, ok? AFAIK you need at least app context to show toast, am i wrong?:) – Arek Wrzos Apr 06 '18 at 09:27
  • i mean you going to test system behavior, not your app and thats the case - your code can be tested by jUnit only – Arek Wrzos Apr 06 '18 at 09:28
  • I am using espresso so I can access the application's Context. I can't test that with jUnit only. – LonsomeHell Apr 06 '18 at 10:36
  • i dont know what are you really going to test? if that method invoked shows toast? is that background/service case? – Arek Wrzos Apr 06 '18 at 10:47
  • It is going to be shown from activities and background services. – LonsomeHell Apr 06 '18 at 11:38