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.

Marta Pyznarska
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.

  1. Download espresso jar from here.
  2. Add espresso-X.X-bundled.jar to the libs directory in your project root (Create this directory if you don’t have it)
  3. Right click on the jar and click ‘Add as Library…’
  4. In the root of your project, create instrumentTest\java directory. (in Android Studio startign from 0.9 it is renamed to androidTest\java)
  5. Right click on the newly created dir and choose ‘Mark directory As Tests Sources Root’
  6. 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)
  7. Create an empty Java Class in the new package for your tests.
  8. 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’)

  1. 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.
  2. Open your Java Test class and fill it with tests. You can use Espresso objects. Check the example Test class here.
  3. If you encounter any errors from IDE, just type gradle clean in the console in the project root.
  4. Run the instrumentation tests, by typing gradle connectedInstrumentTest
  5. This sample Project is ready to to be checkouted and tested. If you run the tests — 2 should pass, 1 should fail.
  6. 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’)
  7. 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.

--

--