Unit testing is an integral part of software development. Hence, this blog focuses on adding unit tests to SUSI.AI Android app. To keep things simple, take a very basic example of anonymize feedback section. In this section the email of the user is truncated after ‘@’ symbol in order to maintain the anonymity of the user. Here is the function that takes ‘email’ as a parameter and returns the truncated email that had to be displayed in the feedback section :
The unit test has to be written for the above function.
Step – 1 : Add the following dependencies to your build.gradle file.
Step – 2 : Add a file in the correct package (same as the file to be tested) in the test package. The function above is present in the Utils.kt file. Thus create a file, called UtilsTest.kt, in the test folder in the package ‘org.fossasia.susi.ai.helper’.
Step – 3 : Add a method, called testTruncateEmailAtEnd(), to the UtilsTest.kt and add ‘@Test’ annotation to before this method.
Step – 4 : Now add tests for various cases, including all possible corner cases that might occur. This can be using assertEquals() which takes in two paramters – expected value and actual value.
For example, consider an email ‘firstname.lastname@example.org’. This email is passed as a parameter to the truncateAtEnd() method. The expected returned string would be ‘testuser@ …’. So, add a test for this case using assertEquals() as :
Similary, add other cases, like empty email string, null string, email with numbers and symbols and so on.
Here is how the UtilsTest.kt class looks like.
Note: You can add more tests to check for other general and corner cases.
Step – 5 : Run the tests in UtilsTest.kt.
If all the test cases pass, then the tests pass. But, if the tests fail, try to figure out the cause of failure of the tests and add/modify the code in the Utils.kt accordingly. This approach helps recognize flaws in the existing code thereby reducing the risk of bugs and failures.
- Build effective unit tests | Android Developers
- Read about JUnit https://junit.org/junit5/
- Read about Mockito https://site.mockito.org