Unit Testing in Android using JUnit
Last Updated :
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 by Step Implementation
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.assertThat
import 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.
Similar Reads
Decorators in Python In Python, decorators are a powerful and flexible way to modify or extend the behavior of functions or methods, without changing their actual code. A decorator is essentially a function that takes another function as an argument and returns a new function with enhanced functionality. Decorators are
10 min read
Sliding Window Technique Sliding Window Technique is a method used to solve problems that involve subarray or substring or window. The main idea is to use the results of previous window to do computations for the next window. This technique is commonly used in algorithms like finding subarrays with a specific sum, finding t
13 min read
AVL Tree Data Structure An AVL tree defined as a self-balancing Binary Search Tree (BST) where the difference between heights of left and right subtrees for any node cannot be more than one. Example of an AVL Tree:The balance factors for different nodes are : 12 :1, 8:1, 18:1, 5:1, 11:0, 17:0 and 4:0. Since all differences
4 min read
What is a Neural Network? Neural networks are machine learning models that mimic the complex functions of the human brain. These models consist of interconnected nodes or neurons that process data, learn patterns, and enable tasks such as pattern recognition and decision-making.In this article, we will explore the fundamenta
14 min read
ArrayList in Java Java ArrayList is a part of the collections framework and it is a class of java.util package. It provides us with dynamic-sized arrays in Java. The main advantage of ArrayList is that, unlike normal arrays, we don't need to mention the size when creating ArrayList. It automatically adjusts its capac
9 min read
Read JSON file using Python The full form of JSON is JavaScript Object Notation. It means that a script (executable) file which is made of text in a programming language, is used to store and transfer the data. Python supports JSON through a built-in package called JSON. To use this feature, we import the JSON package in Pytho
4 min read
Multithreading in Python This article covers the basics of multithreading in Python programming language. Just like multiprocessing , multithreading is a way of achieving multitasking. In multithreading, the concept of threads is used. Let us first understand the concept of thread in computer architecture. What is a Process
8 min read
Two Pointers Technique Two pointers is really an easy and effective technique that is typically used for Two Sum in Sorted Arrays, Closest Two Sum, Three Sum, Four Sum, Trapping Rain Water and many other popular interview questions. Given a sorted array arr (sorted in ascending order) and a target, find if there exists an
11 min read
Python Match Case Statement Introduced in Python 3.10, the match case statement offers a powerful mechanism for pattern matching in Python. It allows us to perform more expressive and readable conditional checks. Unlike traditional if-elif-else chains, which can become unwieldy with complex conditions, the match-case statement
7 min read
Architecture of 8085 microprocessor A microprocessor is fabricated on a single integrated circuit (IC) or chip that is used as a central processing unit (CPU).The 8085 microprocessor is an 8-bit microprocessor that was developed by Intel in the mid-1970s. It was widely used in the early days of personal computing and was a popular cho
11 min read