Add Android unit test to existing android studio project

Here I'm talking about tests that needs Emulator or a device to run, not pure java unit test. For example for testing a provider. The test example is pure java though but it is a simple proof of concept.

Add the following in your build.gradle

apply plugin: 'com.android.application'

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

}
dependencies {
    ...
    // test dependency
    testCompile 'junit:junit:4.12'
    testCompile group: 'org.hamcrest', name: 'hamcrest-core', version: '1.3'
    // AndroidJUnit Runner dependencies
    androidTestCompile 'com.android.support.test:runner:0.3'
    // Set this dependency to use JUnit 4 rules
    androidTestCompile 'com.android.support.test:rules:0.3'
    // Dependency conflict
    androidTestCompile 'com.android.support:support-annotations:22.+'
}

Simple test to put in src/androidTest/java/...

import android.test.suitebuilder.annotation.SmallTest;
import android.support.test.runner.AndroidJUnit4;
import android.support.test.runner.AndroidJUnitRunner;

import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;

import static org.junit.Assert.assertTrue;

/**
 * Created by alex on 18/08/15.
 */
@RunWith(AndroidJUnit4.class)
@SmallTest
public class SimpleTest {

    @Before
    public void before() {
    }

    @Test
    public void myTest() {
        assertTrue(false);
    }

    @After
    public void after() {
    }
}

Alternative to not using JUnit4 is to extend AndroidTestCase

public class TimeZoneCaseTest extends AndroidTestCase {
    public void testFail() {
        assertTrue(false);
    }

    public void testSuccess() {
        assertTrue(true);
    }
}

To run from Android studio IDE, select "Android Instrumentation Tests", then you can right click on the test and select "Run"

If you get errors, lile !!! JUnit version 3.8 or later expected:, it might be because was ran before in the wrong configuration so edit the configuration to make the ruunner is in the "Android Tests" section

To run from the command line:

./gradlew connectedCheck

Or if the test is in a submodule:

./gradlew my-module:connectedCheck

Popular posts from this blog

Simple Samba setup on Lubuntu

Soving AccessDenied on Google Cloud Storage domain mapping

Deploying a static website efficiently on Google Cloud Storage