Testing Snackbar on Android

Barry Carroll
Jul 25, 2017 · 2 min read

The Toast is toast, long live the Snackbar. I show three different types of Snackbar on two of my Activities. Naturally I wanted to add some tests, because tests are good. It is not as easy and robust as it could be.

The resplendent Snackbar in its natural habitat

The challenge is that Snackbar gives you a setText() but it doesn’t give you a getText(). This means that we’re going to have to dig deeper. It’s never going to be as robust as using a proper accessor method, but hey, can’t hurt to have a look.

The following gist was my first attempt, and it is pointlessly complicated. I noticed that Snackbar had a getView() method, so I used the debugger to locate the interesting elements within, specifically the TextView for the error message, and the Button for the Snackbar’s action. Please don’t do it this way.

Do not do it this way

When I finally had a handle on the TextView I saw that it had an ID set, which prompted me to dig into Snackbar’s source code. It didn’t take long to notice that it was inflating a view in the make() method. This view is called R.layout.design_layout_snackbar_include and it looks like this (I’ve omitted stuff for brevity’s sake).

The Snackbar’s layout file: abridged

It is still going to be potentially brittle, but I think that using those IDs is going to be better than messing with the view hierarchy like the first test. Using the IDs, we can rewrite the test like this:

The less bad version

The test now uses the findViewById that we are all well-aware of. One of my colleagues introduced me to the principle of least astonishment, and I think the second example does a better job at following that. It would be better if we had a way of directly testing the Snackbar’s text and action, but this will have to do for now. Thanks for reading!

Barry Carroll

Written by

SDK guy at Zendesk.

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade