Android Studio Unit Test

Unit Test in Android Studio

When you create Android application project, test and androidTest project are created automatically in Android Studio
We may add test codes to these projects.

test project

The difference between test and androidTest are test target

Test Description
test Non Android test. Only Logic, Java general API, not Android API
androidTest Android API related test. If you use Android SDK API in Test, we need to use this. Context, Activity etc…
or other APIs


To use Test library or other library for test, we need to add dependencies to build.gradle

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    androidTestCompile 'junit:junit:4.12'
    testCompile 'junit:junit:4.12'
    testCompile 'org.mockito:mockito-core:1.+'

testCompile ‘junit:junit:4.12’ exists by default.
If you want to use JUnit4 in androidTest, please add androidTestCompile ‘junit:junit:4.12’, maybe no need

Unit Test

Preparation was done.
Let’s start Unit Test for logic


This is blank test for test project

public class FirstTest {
  public void setUp() throws Exception {
  public void tearDown() throws Exception {

  public void testFirst() {
     // Test Code

This is just same as JUnit4 test.


Next is Android Test. When you create project, androidTest folder is created by default.
This is Android Test. Android Test includes Activitiy and any tests with Android API.
Currently, Android Test is JUnit3, not JUnit4. If you want to use JUnit4 add following

dependencies {
  androidTestCompile 'junit:junit:4.12'

The name is androidTestCompile. So you can add test dependencies using androidTestCompile

public class AndroidFirstTest extends AndroidTestCase {

    public void testXxxxx() {

Extend AndroidTestCase and testXxxxx method(start with test)
In AndroidTestCase class, you can get context using getContext();