Running Instrumented Test in Android

An instrumented test is a fancy name for a test that runs within the Android device in the same process space as your app. This lets you test code that relies on Android SDK calls. The official guide is horridly incomplete. Here are a few quick notes.

Package Conflict

Android Studio builds a separate APK just for instrumented test. This runs in the same process space as the APK for the main app. Unfortunately this means both APKs must have no conflicting package dependencies. But the Internet is full of example of conflict with theĀ com.android.support:support-annotations package. You will need to force both APK to use a higher version.

androidTestCompile 'com.android.support.test:runner:0.5'
androidTestCompile 'com.android.support.test:rules:0.5'

//Force same version
androidTestCompile 'com.android.support:support-annotations:23.2.0'
compile 'com.android.support:support-annotations:23.2.0'

This is just an example only. By the time you read this newer versions may be available.

Location of the Test Java File

You have to create the test Java file in theĀ androidTest folder. This way it will get packaged with the test APK.

Annotation

An instrumented test class needs to have @RunWith and @SmallTest annotation.

A sample template class:

import android.support.test.runner.AndroidJUnit4;
import android.test.suitebuilder.annotation.SmallTest;
import org.junit.Test;
import org.junit.runner.RunWith;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;

@RunWith(AndroidJUnit4.class)
@SmallTest
public class InstrumentedTests {
 @Test
 public void testCaching() {
   assertNotNull("Hello");
   assertTrue(true);
   assertEquals("One", "One");
 }
}