Home » Android » android – Gradle, Robolectric, and Espresso

android – Gradle, Robolectric, and Espresso

Posted by: admin June 15, 2020 Leave a comment

Questions:

Has anyone successfully gotten Robolectric and Espresso working (together) when building with Gradle (Android Studio)?

I’ve gotten Robolectric working in Android Studio due largely to Peter Friese’s post http://www.peterfriese.de/android-testing-with-robolectric/, but I’m unsure of how to integrate Espresso due to instrumentRunner/instrumentTest collisions.

Ideally I’d have a directory structure like the following:

 |--src
    └── main (application source - exists)
    └── test (Robolectric unit tests go here - exists)
    └── testEspresso [*new*] (espresso tests go here)

My Gradle+Android knowledge isn’t very extensive, and I’m unsure of whether this is really a feasible thing (time, complexity, and fragility levels aren’t too extreme) given the current state of Gradle+Android and if it is, how to go about doing so. Also in case it’s of relevance, I have 2 different build flavors.

How to&Answers:

For a good example of Robolectric and Espresso working together in harmony, check out this sample project created by the Robolectric team:

https://github.com/robolectric/deckard-gradle

Answer:

Another option, which doesn’t include any “hacks, Gradle plugins, IDE plugins, or IML editing” is http://blog.blundell-apps.com/android-gradle-app-with-robolectric-junit-tests/. Jake Wharton recommended this approach. With this, your Robolectric tests are in a separate Java module, separate from your main project. Espresso code lives with your main project.

Using JW’s double-espresso (https://github.com/JakeWharton/double-espresso) will simplify including Espresso and the dependency management madness that can come with it.

The solution @plackemacher mentioned, deckard-gradle, is still an option and is being maintained, though it does require some hacking/surgery to get working with the IDE.

Update: See the discussion here regarding Robolectric and Gradle (relates to Gradle): https://groups.google.com/forum/#!topic/robolectric/xsOpEwtdTi4/discussion

Update: While I have not used it, this looks to be the ticket. https://github.com/JakeWharton/double-espresso.


For the time being, I elected to create a separate Espresso branch (git) which has the proper testRunner and test directory set. Not a horribly elegant solution… does require some vigilance to keep everything up-to-date, but it’s working for now!

Will definitely change the answer should somebody find a better solution.