Screenshot-testing with Material Design Library
Screenshot testing is an automated testing that helps prevent visual regressions in Android apps. The most popular library for this kind of testing is the Facebook library, screenshot-tests-for-android.
You can follow the docs to implement the library (It is not the goal of this article)
In this article, we are focusing on using the screenshot-testing library with the material views, for example: MaterialCardView, MaterialButton …etc
After implementing the library, you can write your test case like this:
This approach actually works well before using any view from the Material Design library. But when you use a view from the Material Design library, you will face this error:
android.view.InflateException: Binary XML file line #63: Error inflating class com.google.android.material.button.MaterialButton
...
Caused by: java.lang.IllegalArgumentException: The style on this component requires your app theme to be Theme.MaterialComponents (or a descendant).
...
The first thing you will probably do is to check your style in styles.xml and you will probably find something like this:
And you’ll say proudly “Ahh Got ya! 😎” then change the parent theme to be one of the material library like this:
But unfortunately this doesn’t solve the problem🤨, you’ll face the same error:
android.view.InflateException: Binary XML file line #63: Error inflating class com.google.android.material.button.MaterialButton
...
Caused by: java.lang.IllegalArgumentException: The style on this component requires your app theme to be Theme.MaterialComponents (or a descendant).
...
Indeed you still need to use one of the material themes to get it working, but you will need to make a little change in the test case code itself. You will need to use a themed context instead of the regular context. So the solution can be summarized in two simple steps:
- Use a material theme
- Use a themed context
You’ll just modify your test case by adding this simple line
val themedContext = ContextThemeWrapper(context, R.style.AppTheme)
So that the final code looks like this:
That’s it.
I hope that this article can help someone in the future because I was struggling against this error for a long time and finally could solve it with the help of Hilal Alsibai in this issue.