Unit Testing in Android using JUnit - GeeksforGeeks

18 Dec, 2021
Unit testing is done to ensure that developers write high-quality and errorless code. It is advised to write Unit tests before writing the actual app, you will write tests beforehand and the actual code will have to adhere to the design guidelines laid out by the test. In this article, we are using JUnit to test our code. 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. Here we will be using only @Test annotation to keep the article easy to understand. Note that we are going to implement this project using the Kotlin language.
Step 1: Create a new Project
To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Kotlin as the programming language.
Step 2: Add dependency to the build.gradle file and click “sync now”
    testImplementation “com.google.truth:truth:1.0.1”
   androidTestImplementation “com.google.truth:truth:1.0.1”
Step 3: Working with the RegistrationUtil.kt file
Create a new Kotlin file RegistrationUtil and choose its type as an object. Since this is a singleton we do not need to create an object of it while using it in other classes. It has a function called validRegistrationInput which requires three arguments username, password, and confirm password. We will be testing this function with different sets of inputs with the following test cases.
Username, password, confirm password should not be empty.
Password must contain at least two digits.
Password matches the confirmed password.
Username must not be taken.
Kotlin
object RegistrationUtil {     private val existingUsers = listOf("Rahul" , "Rohan")     /**     * The test cases will pass if..     * ...username/password/confirmPassword is not empty     * ...password is at least 2 digits     * ...password matches the confirm Password     * ...username is not taken     */    fun validRegistrationInput(        userName : String,        password : String,        confirmPassword : String    ) : Boolean {        // write conditions along with their return statement        // if username / password / confirm password are empty return false        if (userName.isEmpty() || password.isEmpty() || confirmPassword.isEmpty()){            return false        }        // if username exists in the existingUser list return false        if (userName in existingUsers){            return false        }        // if password does not matches confirm password return false        if (password != confirmPassword){            return false        }        // if digit count of the password is less than 2 return false        if (password.count { it.isDigit() } < 2){            return false        }        return true    }}
Step 4: Create a test class
In order to create a test class of RegistrationUtil right-click on RegistrationUtil then click generate and then select the test. A dialog will open, from the dialog choose Testing library as JUnit4 and keep the class name as default that is RegistrationUtilTest, and click ok. After that, another dialog will open to choose the destination directory, choose the one which has ..app\src\test\. because our test class does not require any context from the application. Below is the screenshot to guide you create the test class.
Step 5: Working with RegistrationUtilTest.kt file
Go to RegistrationUtilTest.kt file and write the following code.  Comments are added inside the code to understand the code in more detail.
Kotlin
import com.google.common.truth.Truth.assertThatimport org.junit.Test class RegistrationUtilTest {    // Write tests for the RegistrationUtil class considering all the conditions    // annotate each function with @Test    // We can use backtick to write function name..    // whatever we write in those backtick will be considered as function name    @Test    fun `empty username returns false`(){        // Pass the value to the function of RegistrationUtil class        // since RegistrationUtil is an object/ singleton we do not need to create its object        val result = RegistrationUtil.validRegistrationInput(            "",            "123",            "123"        )        // assertThat() comes from the truth library that we added earlier        // put result in it and assign the boolean that it should return        assertThat(result).isFalse()    }     // follow the same for other cases also    // in this test if username and correctly repeated password returns true    @Test    fun `username and correctly repeated password returns true`() {        val result = RegistrationUtil.validRegistrationInput(            "Rahul",            "123",            "123"        )        assertThat(result).isTrue()    }     // in this test userName already taken returns false    @Test    fun `username already taken returns false`() {        val result = RegistrationUtil.validRegistrationInput(            "Rohan",            "123",            "123"        )        assertThat(result).isFalse()    }     // if confirm password does nt matches the password return false    @Test    fun `incorrect confirm password returns false`() {        val result = RegistrationUtil.validRegistrationInput(            "Rahul",            "123",            "1234"        )        assertThat(result).isFalse()    }     // in this test if password has less than two digits than return false    @Test    fun `less than two digit password return false`() {        val result = RegistrationUtil.validRegistrationInput(            "Rahul",            "abcd1",            "abcd1"        )        assertThat(result).isFalse()    }}
Step 6: Run the Test cases
To run the test case click on the little run icon near the class name and then select Run RegistrationUtilTest. If all the test cases pass you will get a green tick in the Run console. In our case, all tests have passed.
Github repo here.
 
sumitgumber28
Technical Scripter 2020
Android
Kotlin
Technical Scripter
Android
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Resource Raw Folder in Android Studio
Flutter - Custom Bottom Navigation Bar
How to Read Data from SQLite Database in Android?
How to Post Data to API using Retrofit in Android?
Retrofit with Kotlin Coroutine in Android
Android UI Layouts
Kotlin Array
Retrofit with Kotlin Coroutine in Android
How to Get Current Location in Android?
Kotlin Setters and Getters