Android Writing Your OwnTest Cases

The Android framework includes an integrated testing framework that helps you test all aspects of your application and the SDK tools include tools for setting up and running test applications.

But at times you would require to write your own test cases to ensure that things work smoothly. There are different frameworks in android for the same. Few are listed below:

  1. JUnit
  2. Mockito
  3. Powermock
  4. Robolectric
  5. Espresso
  6. Hamcrest

Below is an example of JUnit

JUnit is a “Unit Testing” framework for Java Applications which is already included by default in android studio. It is an automation framework for Unit as well as UI Testing. It contains annotations such as @Test, @Before, @After, etc.

So let’s begin

  1. Set up the test environment:

In addition, to run Instrumented Unit test, we must add AndroidJUnitRunner

2. Create JUnit Test Class:

# Creating Local Test

Prior Android Studio 2.0.0: Open the Build Variants window by clicking the left-hand tab, then change the test artifact to Unit Tests.

The JUnit test class should be located at: app/src/test/java folder. Example; JUnit Test called CalculatorTest.java

# Creating Instrumented Test

Prior Android Studio 2.0.0: Open the Build Variants window by clicking the left-hand tab, then change the test artifact to Android Instrumentation Tests.

The JUnit Instrumented test class should be located at: app/src/androidTest/java folder. Example; JUnit Instrumented Test called LogHistoryAndroidUnitTest.java

3. Run the Test.

We must chose the test artifact from Build Variants window to run either of those unit test. To run specific unit test class or method, right-click on it and Run ’test name’ it. To run all tests in the unit test directory, select the directory then right-click and press Run test.

Ta-da that’s it. Keep Coding!!