One of the great new features of Android Studio 2.0 is the automatic implementation of unit testing when you create a new project. However, in it’s base form, it’s only good for testing Java code (nothing Android specific). Mocking an instance of Context won’t do any good if you need it to execute your code.
The solution is…
Robolectric
The only drawback to this method, is that it doesn’t currently support Api level 22 and above. You will need to adjust the following in your build.gradle…
compileSdkVersion 21 buildToolsVersion "21.1.2"
You will also need to change the version of appcompat you’re using
compile 'com.android.support:appcompat-v7:21.0.0'
Add the following line into the dependencies section
testCompile "org.robolectric:robolectric:3.0"
So all said and done, your build.gradle file should look similar to this
apply plugin: 'com.android.application' android { compileSdkVersion 21 buildToolsVersion "21.1.2" defaultConfig { applicationId "net.evanp.umactuallynerdtriviagame" minSdkVersion 15 targetSdkVersion 21 versionCode 1 versionName "1.0" } buildTypes { release { minifyEnabled false proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' } } } dependencies { compile fileTree(dir: 'libs', include: ['*.jar']) testCompile 'junit:junit:4.12' testCompile "org.robolectric:robolectric:3.0" compile 'com.android.support:appcompat-v7:21.0.0' }
Editing your test classes
Before your class is declared, add the following
@RunWith(RobolectricGradleTestRunner.class) @Config(constants = BuildConfig.class)
On top of the test method add @test just like usual, but notice how the instance of Context is created
@Test public void testAbilityToAccessXML() throws Exception { Context context = RuntimeEnvironment.application.getApplicationContext(); ProgramWideFunctions.randomCategory(context); }
It’s that easy!