androidrobolectricandroid-snackbar

android snackbar - how to test with roboelectric


From here we now know that robolectric does not have a shadow object but we can create a custom shadow object for a snackbar.It's ashame they have one for toast but not for snackbar.

I am showing a snackbar in my code when there is no network connection. I'd like to know how can i write a unit test (with robolectric as the test runner) that can verify that a snackbar gets shown when there is no network connection.

Its a little hard because the snackbar is not in xml. So when i declare my actually Activity controller it doesn't have a snackbar at that time.

You know how to test a toast we have ShadowToast.getTextOfLatestToast() i want one for snackBar

im currently using org.robolectric:robolectric:3.0-rc2 and dont see ShadowSnackbar.class available.


Solution

  • It's actually explained in the blogpost how to add the ShadowToast class to enable testing.

    1. Add the ShadowSnackbar to your test sources;
    2. Add the Snackbar class as an instrumented class in your custom Gradle test runner;
    3. Add the ShadowSnackbar as a Shadow in your test;

    In your app's code, you'll call on the Snackbar when no internet connection is available. Because of the configuration (e.g. intercepting of) the Snackbar as Instrumented class, the Shadow-variant of the class will be used. You'll be able to evaluate the result at that moment.