Testing Snackbar on Android
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 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.
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).
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 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!
