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
Unit Testing in Android using Mockito
Most classes have dependencies, and methods frequently delegate work to other methods in other classes, which we refer to as class dependencies. If we just utilized JUnit to unit test these methods, our tests would likewise be dependent on them. All additional dependencies should be independent of t
4 min read
Testing Room Database in Android using JUnit
In this article, we are going to test the Room Database in android. Here 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 an
5 min read
UI Testing with Espresso in Android Studio
UI testing is the process of testing the visual elements of an application to ensure whether they appropriately meet the anticipated functionality. Verifying the application manually whether it works or not is a time taking and tiring process, but using espresso we can write automated tests that run
6 min read
Lint and its Usage in Android Studio
As Android Developers, we all utilize Android Studio to create our apps. There are numerous alternative editors that can be used for Android app development, but what draws us to Android Studio is the assistance that it offers to Android developers. The assistance may take the shape of auto-suggesti
6 min read
Buddy Testing in Software Testing
Buddy Testing as the name suggests involves two team members, one from the development team and one from the testing team. The article focuses on discussing Buddy Testing. The following topics will be discussed here: Table of Content What is Buddy Testing?Importance of Buddy TestingTypes of Buddy Te
9 min read
Android Studio Main Window
Android Studio is the official IDE (Integrated Development Environment) for Android app development and it is based on JetBrainsâ IntelliJ IDEA software. Android Studio provides many excellent features that enhance productivity when building Android apps, such as: A blended environment where one can
4 min read
How to Run Only One Unit Test Class Using Gradle?
This article focuses on discussing how to run a specific unit test class using Gradle by specifying the fully qualified name of the test class. One can use the test task and the --tests option followed by the fully qualified name of the test class. We will see all the aspects in this article.What is
6 min read
How to Test Java Application using TestNG?
TestNG is an automation testing framework widely getting used across many projects. NG means âNext Generationâ and it is influenced by JUnit and it follows the annotations (@). Â End-to-end testing is easily handled by TestNG. As a sample, let us see the testing as well as the necessity to do it via
4 min read
First Android Application in Kotlin
We can build an Android application using Kotlin and Java. In the Android Studio Kotlin Tutorial, we are using Kotlin language to build the application. In the previous tutorial, we learned how to create a project for Kotlin language but here, we will learn how to run an application using the AVD (A
2 min read
Testing an Android Application with Example
Testing is an essential part of the Android app development process. It helps to ensure that the app works as expected, is bug-free, and provides a seamless user experience. Android offers various testing tools and frameworks that can be used to write and execute different types of tests, including
5 min read