UI Tests with Espresso — Android Studio
5 minutes set up for beginners who wish to introduce Android UI Test based on Espresso framework in Android Studio.
2 min readJan 18, 2014
You have your Android project. You use Android Studio. You want to easily write tests for your UI. You don’t have Roboelectric’s unit tests.
- Download espresso jar from here.
- Add espresso-X.X-bundled.jar to the libs directory in your project root (Create this directory if you don’t have it)
- Right click on the jar and click ‘Add as Library…’
- In the root of your project, create instrumentTest\java directory. (in Android Studio startign from 0.9 it is renamed to androidTest\java)
- Right click on the newly created dir and choose ‘Mark directory As Tests Sources Root’
- Right click on the directory and choose new package, then enter your package name (probably you want to name it sth like your.package.name.tests)
- Create an empty Java Class in the new package for your tests.
- In the build.gradle file in the dependencies section add instrumentTestCompile files('libs/espresso-1.1-bundled.jar')
Note: it was changed to androidTestCompile files(‘libs/espresso-1.1-bundled.jar’)
- In the build.gradle file in the android.defaultConfig section add testInstrumentationRunner “com.google.android.apps.common.testing.testrunner.GoogleInstrumentationTestRunner”. Check the full gradle build file here.
- Open your Java Test class and fill it with tests. You can use Espresso objects. Check the example Test class here.
- If you encounter any errors from IDE, just type gradle clean in the console in the project root.
- Run the instrumentation tests, by typing gradle connectedInstrumentTest
- This sample Project is ready to to be checkouted and tested. If you run the tests — 2 should pass, 1 should fail.
- You can open the result page of your test in the browset (open build\reports\…\index.html in your browser — can be done by right clicking on the file in AS and choosing ‘Open in Browser’)
- Do some more real tests and enjoy.
You can catch me easily at Twitter @MartaRylko
———EDIT
Irrepracable Jack Wharton made a pure Gradle port: https://github.com/JakeWharton/double-espresso so you may want to actually use that and not the above instruction.