Working with Test Driven Development(TDD) in Android with Kotlin
Last Updated :
14 May, 2023
TDD is a software methodology, in which developers write tests for pieces of code prior to writing the code itself. If you are unfamiliar with this buzzword, please read this article first. In TDD, the test has to be written, followed by writing the code. The test may fail, the code will be updated, again it may fail, again the code is changed, and the process goes on till the code passes the test. There are a lot of advantages to implementing this methodology:
- So basically, the code is written so that it matches that of the test. In this way, the developer is able to make a product that matches the expectations of the product. The implementation can happen much faster because everything is pre-planned.
- There is a level of confidence since the tests are pre-defined, and if the code passes the test, then that means the code is working as expected.
- If the tests are written after coding, then the developer may unknowingly write tests that will work around the code, making a different product from what was planned earlier. With TDD, no such problem occurs.
After reading the advantages, one might think that this methodology is the best, every firm should adopt it to make their product the best. But in practice, adopting and implementing this methodology can be quite tricky. There might be cases, where you write code, that won't even compile, because tests are written before the code itself, which will cause a compile-time error. Writing tests that don't compile is a significant barrier to entry for TDD.
Implementing TDD Effectively
Irrespective of the difficulty of implementing TDD, developers still work around such a method. Let us see how one can implement TDD effectively. For this purpose, we will make a simple single-activity Android Application in Kotlin.
Minimal Example
Let us create a StudentDetailViewModel. A Student model will conditionally show some information about a student in a particular class. The information will include the student's name, roll number, date of birth, address, and gender.
Step 1: Create a New Project in Android Studio
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: Adding Dependencies
To use TDD, we need to add the necessary dependencies in the build.gradle (app) file. Add the following dependencies:
dependencies {
implementation 'androidx.lifecycle:lifecycle-livedata-core-ktx:2.5.1'
testImplementation 'junit:junit:4.13.2'
testImplementation 'org.mockito:mockito-core:3.11.2'
testImplementation 'org.robolectric:robolectric:4.6.1'
}
Step 3: Writing Tests
Now that we have added the necessary dependencies, let's write our first test case for the StudentDetailViewModel. Create a new Kotlin file under the src/test/java directory and name it StudentDetailViewModelTest. In the StudentDetailViewModelTest class, let's write a test case that verifies the ViewModel is correctly instantiated.
Kotlin
@RunWith(RobolectricTestRunner::class)
class StudentDetailViewModelTest {
private lateinit var viewModel: StudentDetailViewModel
@Before
fun setUp() {
viewModel = StudentDetailViewModel()
}
@Test
fun testViewModelInstantiation() {
assertNotNull(viewModel)
}
}
In the above code, we have created an instance of the StudentDetailViewModel in the setUp() method and verified that the instance is not null in the testViewModelInstantiation() method.
Step 4: Writing the production code
Now that we have written our first test case, let's write the production code that passes this test case. Create a new Kotlin file under the src/main/java directory and name it StudentDetailViewModel. Add the following code:
Kotlin
class StudentDetailViewModel {
private val _studentInfo = MutableLiveData<Student>()
val studentInfo: LiveData<Student>
get() = _studentInfo
fun loadStudentInfo(studentId: String) {
val student = Student(
name = "Ideal Name",
rollNumber = "20",
dateOfBirth = "2000-01-01",
address ="Ideal Address",
gender = "Male"
)
_studentInfo.value = student
}
}
Defining the Student Data class:
Kotlin
data class Student(
val name: String,
val rollNumber: String,
val dateOfBirth: String,
val address: String,
val gender: String
)
Step 5: Writing More Tests
Let's add more test cases to the StudentDetailViewModelTest class to test the functionality of the StudentDetailViewModel:
Kotlin
@RunWith(RobolectricTestRunner::class)
class StudentDetailViewModelTest {
private lateinit var viewModel: StudentDetailViewModel
@Before
fun setUp() {
viewModel = StudentDetailViewModel()
}
@Test
fun testViewModelInstantiation() {
assertNotNull(viewModel)
}
@Test
fun testLoadStudent() {
// Set up
val studentDetailViewModel = StudentDetailViewModel()
val expectedName = "Ideal Name"
val expectedRollNo = "20"
val expectedDob = "2000-01-01"
val expectedAddress = "Ideal Address"
val expectedGender = "Male"
val rollNo = "20"
// Exercise
studentDetailViewModel.loadStudentInfo(rollNo)
// Verify
assertEquals(expectedName, studentDetailViewModel.studentInfo.value?.name ?: "")
assertEquals(expectedRollNo, studentDetailViewModel.studentInfo.value?.rollNumber)
assertEquals(expectedDob, studentDetailViewModel.studentInfo.value?.dateOfBirth ?: "")
assertEquals(expectedAddress, studentDetailViewModel.studentInfo.value?.address ?: "")
assertEquals(expectedGender, studentDetailViewModel.studentInfo.value?.gender ?: "")
}
}
Step 6: Running the test
To run the tests in Android Studio, you can follow these steps:
- In the Project view, navigate to the directory that contains your test file(s).
- Right-click on the file you want to run and select "Run 'Tests in ...'" from the context menu.
- The test runner will launch and execute your tests
Once the tests have finished running, you can view the results in the "Run" tab at the bottom of the screen.
Test Result
If the test passes, you will see Test Passed Message in the Run console:
You can add more tests in the StudentDetailViewModelTest.
Conclusion
In this article, we have learned how to implement Test-Driven Development (TDD) approach in an Android app using Kotlin and the Android ViewModel architecture. We started by defining a simple Student model and a StudentDetailViewModel that provides information about a student's details. We then wrote tests for our view model, making sure that it satisfies the requirements we have defined. With the tests in place, we could write the view model code that meets those requirements, iterating until all tests passed.
Similar Reads
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
Android Architecture Android architecture contains a different number of components to support any Android device's needs. Android software contains an open-source Linux Kernel having a collection of a number of C/C++ libraries which are exposed through application framework services. Among all the components Linux Kern
5 min read
States of a Process in Operating Systems In an operating system, a process is a program that is being executed. During its execution, a process goes through different states. Understanding these states helps us see how the operating system manages processes, ensuring that the computer runs efficiently. Please refer Process in Operating Sys
11 min read
Android Tutorial In this Android Tutorial, we cover both basic and advanced concepts. So whether you are a fresher (graduate) or an experienced candidate with several years of Android Development experience, you can follow this Android tutorial to kick-start your journey in Android app development. Our Android Tutor
15+ min read
Activity Lifecycle in Android with Demo App In Android, an activity is referred to as one screen in an application. It is very similar to a single window of any desktop application. An Android app consists of one or more screens or activities. Each activity goes through various stages or a lifecycle and is managed by activity stacks. So when
9 min read
Introduction to Android Development Android operating system is the largest installed base among various mobile platforms across the globe. Hundreds of millions of mobile devices are powered by Android in more than 190 countries of the world. It conquered around 71% of the global market share by the end of 2021, and this trend is grow
5 min read
Android UI Layouts Layouts in Android define the user interface and hold UI controls or widgets that appear on the screen of an application. Every Android application consists of View and ViewGroup elements. Since an application contains multiple activitiesâeach representing a separate screenâevery activity has multip
5 min read
Top 50 Android Interview Questions and Answers - SDE I to SDE III A Linux-based open-source OS, Android was created by Andy Rubin and became one of the most popular smartphone operating systems. With 71 percent of the market share worldwide, Android is on top. Because it is on top in the smartphone OS, Android development is always in demand.If you are seeking a j
15+ min read
Components of an Android Application There are some necessary building blocks that an Android application consists of. These loosely coupled components are bound by the application manifest file which contains the description of each component and how they interact. The manifest file also contains the appâs metadata, its hardware confi
3 min read
Kotlin Tutorial This Kotlin tutorial is designed for beginners as well as professional, which covers basic and advanced concepts of Kotlin programming language. In this Kotlin tutorial, you'll learn various important Kotlin topics, including data types, control flow, functions, object-oriented programming, collecti
4 min read