Create and run junit tests in Android Studio

When you create a new project in Android Studio, there are three folders created automatically for you.
app/src/main/java – for the source code of your main application build
app/src/test/java – for unit tests that can run on the JVM, a sample test class will be created by Android Studio
app/src/androidTest/java – for tests that need to run on an Android device

The sample unit test class. You can modify this class or create new test class in the same directory as long as the code you want to test doesn’t require Android sdk.

import org.junit.Test;

import static org.junit.Assert.*;

 * To work on unit tests, switch the Test Artifact in the Build Variants view.
public class ExampleUnitTest {
    public void addition_isCorrect() throws Exception {
    	int expected = 5;
    	int actual = Util.addition(2, 3); // pretend this is a static method in the Util class in your android project
        assertEquals(expected, actual);


Follow the following steps to create and run junit tests fo the code that that can run on the JVM.

1. Add the junit library to the dependencies in your gradle file.

dependencies {
   // more stuff...

    // Unit testing dependencies
    testCompile 'junit:junit:4.12'
    // Set this dependency if you want to use the Hamcrest matcher library
    testCompile 'org.hamcrest:hamcrest-library:1.3'

2. To run the junit test from the command line in your android project folder. It will run all the test classes in app/src/test/java. The test result will be in a html page located in app/build/reports/tests/debug/

./gradlew test

3. To run the junit test classes from Android Studio:

  1. Change your directory view from Android to Project View in the Directory naviation.
  2. Select Unit Tests from the Build Variants located on the left directory naviation menu.
  3. Then right click the test file and hit run. The next time, you can just click the run button.

Search within Codexpedia

Custom Search

Search the entire web

Custom Search