Unit Testing in Android Application

Posted By : Prince Bhardwaj | 29-Dec-2017

Unit Testing in Android -

 

     A unit test verifies in isolation the functionality of certain component. For example, suppose a button in an activity is used to start another activity.A unit test would determine, if the corresponing intent was issued, not if the second activity was started.

     Unit Tests for an android application can be -

       1. Local unit tests - runs on JVM.

       2. Android unit tests - runs on android runtime.

     If runs on JVM, they are executed against modified version of android.jar Android library.

 

Note - The local unit tests of an android project should be located in the app/src/test folder. 

 

Running the unit tests -  

 

     1. Using Gradle

         Run your unit test with gradlew test command.

     2. Using android studio

         To run a unit test, right click on your test class in the project window and select run.

 

Location of Test Reports -

 

     The test reports are created in the app/build/reports/tests/debug directory. The index.html file provides overview and also links to individual test       pages. 

 

How to Activate default return values for mocked methods in android.jar -

 

     By default, all call to the methods in the modified android.jar file throw exceptions. This default should ensure that your unit tests only test your code and do not depend on any particular android platform. If you want to configure a certain behaviour, you can use a mocking framework to replace these calls.

     You cal also configure the grable build system to return defailt values for the method calls in android.jar file with the following confriguration in gradle build file -

android {
  //....
  testOptions{
    unitTests.returnDefaultValues = true
  }
}
 

 

Create Unit Test -

 

1. Create Android Project

2. Add JUnit dependency -

dependencies {
    //  Add Unit testing dependencies
    testCompile 'junit:junit:4.12'
}
 

3. Create Test - 

 

In your app/src/test directory, crete a test method. For example -

 @Test
    public void testConvertFahrenheitToCelsius() {
        float actualValue = ConverterUtil.convertCelsiusToFahrenheit(100);
        //expected value is 212.
        float expectedValue = 212;
        //use this method because float is not precise.
        assertEquals(" Conversion from celsius to fahrenheit failed", expectedValue, actualValue, 0.001);
    }
 

 

4. Run your test -

Ensure that your unit tests are correctly implemented by running test tests. They should run successfully.

 

 

 

    

 

 

Related Tags

About Author

Author Image
Prince Bhardwaj

Prince Bhardwaj is having Talent as Application Developer, he is an enthusiastic team player in Oodles Technologies.

Request for Proposal

Name is required

Comment is required

Sending message..