Hello World! Android Unit Testing with Espresso

Tackling android unit testing has more than one approach. A library file or class file(s) without android dependencies can utilize JUnit or any other Java unit testing framework. However, as soon as the code that you want to test is dependent on Activity Context you write instrumentation tests that execute on actual devices or virtual devices.

alt text

Instrumentation tests save the developer time because the tests should run in seconds – and provide a safety net of regression testing. You are actually testing your Android code.

Historically extending ApplicationTestCase can have UI timing (thread synchronization) issues – and getting around these issues involves the “guess sprinkling” of sleep statements in your test code (reminiscent of the web browser automation tool Selenium).

The latest version of Android Studio provides the developer with Espresso included in the Android Testing Support Library. And yes no one is forcing you to stop using Robolectric if desired. However, I believe the fluid API of Espresso makes it (and feels) easier to find views, perform actions, and verify state.

onView(withId(R.id.txtHello))
	.check(matches(withText("")));
onView(withId(R.id.btnHello))
	.check(matches(withText(R.string.clickme)))
	.perform(click());
onView(withId(R.id.txtHello))
	.check(matches(withText(R.string.helloworld)));
onView(withId(R.id.btnHello))
	.check(matches(not(isEnabled())));

And yes, JUnit tests tend to be faster than Espresso tests since they can avoid context and the android framework.

Important for your app’s build.gradle -

defaultConfig { 
	testInstrumentationRunner 'android.support.test.runner.AndroidJUnitRunner'
}

And then utilize your project’s Build Variants to toggle between JUnit tests and Espresso tests.

Get up and running with Espresso using a sample Android Studio project.

Android Studio 1.5.1 JUnit 4.1.1 Espresso 2.+ Android Support Library 23.1.1