Instrumented Unit Tests :
These are unit tests that run on real devices instead of JVM . Using instrumented Unit Tests, we can have real implementation of an Android Framework component like SharedPreferences objects, context of an Activity etc. Also , we will not have to mock any objects.1. Add the following Dependencies :
androidTestCompile 'com.android.support:support-annotations:23.4.0'
androidTestCompile 'com.android.support.test:runner:0.4.1'
androidTestCompile 'com.android.support.test:rules:0.4.1'
// Optional -- Hamcrest library
androidTestCompile 'org.hamcrest:hamcrest-library:1.3'
note that we are using androidTestCompile as instrumented tests will be inside androidTest folder.
2. Specify AndroidJUnitRunner as the default test instrumentation runner in your build.gradle file :
android {
defaultConfig {
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
}
3. Create a Class ”InstrumentedUnitTest” inside src/androidTest/java/com.packagename folder and add @RunWith(AndroidJUnit4.class)
annotation at the beginning of this class.
4. Create one test inside this class . Final class will be like below.
import android.content.Context;
import android.content.SharedPreferences;
import android.support.test.InstrumentationRegistry;
import android.support.test.runner.AndroidJUnit4;
import android.test.suitebuilder.annotation.SmallTest;
import org.junit.Test;
import org.junit.runner.RunWith;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
@RunWith(AndroidJUnit4.class)
@SmallTest
public class InstrumentedUnitTest {
private final String prefName = "TEST_PREF";
@Test
public void test_sharedPref(){
Context mContext = InstrumentationRegistry.getContext();
SharedPreferences mSharedPreferences = mContext.getSharedPreferences(prefName,Context.MODE_PRIVATE);
SharedPreferences.Editor editor = mSharedPreferences.edit();
editor.putString("key", "value");
editor.apply();
SharedPreferences mSharedPreferences2 = mContext.getSharedPreferences(prefName, Context.MODE_PRIVATE);
assertThat("value", is(mSharedPreferences2.getString("key", null)));
}
}
5. Thats it.Run this test. Right click on this file -> Run “InstrumentedUnitTest” ->select your device/emulator ( remember , we are running this test on a real device, not like our previous unit testing tutorials) and click “OK”.
One message will appear like below if everything works fine :
That’s it :) .