Testing is an integral part of every application to ensure the accuracy and stress the code with every possible input and situation. but why? If you believe that user will always follow the instructions then you are leaving some loopholes in applications and don’t forget, some people always wants to see the world burns (hackers?, bounty hunters).
Android has a strict deadline of 5 seconds to respond to user input if failed then it will produce a ANR dialog and crash the application.
Factors needs to be tested:
- Unexpected inputs
- Application Performance (memory, cpu consumption)
- Logic validation
Android offers two way to test applications
- Instrumentation : Allows you to test applications UI on device or emulator
- JUnit : Allows you to test the application logic
Instrumentation Testing: There are many framework available to test application UI and behaviour.
- Espresso: One of the most famous testing framework to test UI. It allows to perform click and other operations, flexible to write customise validators or matchers.
Read more about Espresso Testing
- UI-Automator: To test functionalities like files, wifi setting and perform operation outside your applications UI-Automator is the only way to do it.
- Appium: if you want to write tests for cross platform app, Appium is one of the most popular platform to write tests although it requires various plugins for different platform and configurations which is an occupational hazard I suppose.
Unit Testing: The process of testing the logic of every method is known as Unit testing. It simply beings with creating the instance of the class, mocking the dependencies and invoking the desired methods by passing the desired inputs if required.
- Mockito: It’s one of the popular framework to stub method calls with dummy values to test the code logic. Assume you have a method `getTotal()` which can accepts any number of values but internally use another method `getTaxPercantage()` which returns the tax percentage so in order to only test `getTotal()` independent of `getTaxPercantage()` method , you can simply set a fix default return value of `getTaxPercantage()` method (shown below), hence it’s called mocking.
Mockito cannot mock static and final calls so there are also another popular framework available like `PowerMock`, `EasyMock` etc
- Robolectric: Often code in activities, fragments, adapters are lifecycle dependent and required the `Context` to work so robolectric allows to create an object of an activity while satisfying the need of lifecycle and context.
- Junit: Allows to run test methods in an automative way and also provide validation assertion methods to validate the objects or their values and primitive values.
Note: Test runners are used to run the test methods and provide the result on the screen. They also provide different-2 features to execute settings or clean up methods etc