Android tests with Roboelectric: SnackbarShadow update

If you are an Android developer and you use Roboelectric and Snackbars, you may have ran into some issues when testing Snackbars.

The first time I came across with some issues was in 2015, and it was then when I found out (thanks to this post) the use of custom shadows in Roboelectric.

So, what are custom shadows?

Custom shadows are a Robolectric feature that allows you to make targeted changes in the way Android functions under test.

When I started using the ShadowSnackbar class provided in the post I mentioned, everything went spectacular; until now.

The problem

I started adding some tests into a new project (using design-library v25) and because I had to test some snackbars, I decided to copy the ShadowSnackbar class of a previous project.

After running some tests, I encountered this error:


Checking the ShadowSnackbar class, I found out that the Snackbar constructor implementation had changed, so it was failing when trying to get a new instance of the Snackbar using Java Reflection.

These are the Snackbar constructors:
Before API 25

private Snackbar(ViewGroup parent) {
mTargetParent = parent;
mContext = parent.getContext();


LayoutInflater inflater = LayoutInflater.from(mContext);
mView = (SnackbarLayout) inflater.inflate(
R.layout.design_layout_snackbar, mTargetParent, false);

mAccessibilityManager = (AccessibilityManager)


API 25:

private Snackbar(ViewGroup parent, View content, ContentViewCallback contentViewCallback) {
super(parent, content, contentViewCallback);

To make the tests run I needed to change the ShadowSnackbar implementation to allow me to create a Snackbar instance using the new constructor.

The new implementation looks like this:

If you ran into the same issue with the new design library, do not waste your time and start using this new implementation.

Like what you read? Give Juan Manuel Pereira a round of applause.

From a quick cheer to a standing ovation, clap to show how much you enjoyed this story.