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: ''

android {
    defaultConfig {
        testInstrumentationRunner ''

dependencies {
    // test dependency
    testCompile 'junit:junit:4.12'
    testCompile group: 'org.hamcrest', name: 'hamcrest-core', version: '1.3'
    // AndroidJUnit Runner dependencies
    androidTestCompile ''
    // Set this dependency to use JUnit 4 rules
    androidTestCompile ''
    // Dependency conflict
    androidTestCompile ''

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

import android.test.suitebuilder.annotation.SmallTest;

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.
public class SimpleTest {

    public void before() {

    public void myTest() {

    public void after() {

Alternative to not using JUnit4 is to extend AndroidTestCase

public class TimeZoneCaseTest extends AndroidTestCase {
    public void testFail() {

    public void testSuccess() {

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