Android UnitTest

Android UnitTest

Table of Contents

  • kinds of Unit Tests in Android
  • Android Instrument Test
  • Junit Test
  • the Demo
Unit Test was always the most import part of a project, especially for Object-oriented programming like Java codes, and also was the necessary part of Test-Driven Development technology. But how to process test-driven technology in Android app developement, we all know that android app is based on Java code, and the thought of TDD was in the blood of Java. There are must be some ways to do TDD in Android, and this article will guide you to the Unit test in Android Development.

1 kinds of Unit Tests in Android

There are two levels of Unit Test in Android, Android Instrument Test, which running in the Android Devices; and Junit Test, which running without any Android environment.

The key difference between two of them are the dependency on the android.jar, in other word, the Android API. We develop android app by import the dependency of android.jar, which collected all the Android API. So what the API is? short for Application Programming Interface, yeah, it is the interface without the implementation, and the implementation was inside the Android device, that's why we need to install the test app, in order to run it.

So if your code is just pure java code without dependency on android.jar, you can run your test code in Junit framework in every where.

In sum, Android Test Instrument is to test Android component behaver, and the Junit test case is used to test logical and functional parts of the App.

2 Android Instrument Test

The Android doc described it very well. so following it.

Android Studio support this kinds of test very well, all you need to do is to configure run dialog in the right way. After I code the unit test, following is the mistakes I met to run it.
  • make sure the unit test item in Run/Debug Configurations is in the Android Tests part instead of the Junit part.
  • remember to unlock the phone's screen when you wanna test the UI interaction.

3 Junit Test

As described in the first section, Junit test can be running in the command line directly.

./gradlew test

add following lines into build.gradle to disable the unimportant android.jar reference.

android {
    ...

    testOptions {
        unitTests.returnDefaultValues = true
    }
}

dependencies {
   testCompile 'junit:junit:4.12'
   testCompile 'org.mockito:mockito-core:1.9.5'
}

If your code imported the utils classes in the Android.jar like android.util.Log, you need to add above line to let junit ignore the class unfounded exception.

Also noticed is that the keyword testCompile, which means the dependency in test directory. Basically, I collect the Junit test in test directory, and the Android Test cases in androidTest directory.

Comments

Popular posts from this blog

Bluedroid stack in android

How to setup a NAT server?

Network programming in elisp