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
Master Android Development With Kotlin: A Complete Guide
We regret to inform you that the Android App Development with Kotlin â Live Course by GeeksforGeeks is currently unavailable. For information on related courses and opportunities, please click here.Thank you for your interest.
1 min read
Convert WebView to PDF in Android with Kotlin
Sometimes the user has to save some article that is being displayed on the web browser. So for saving that article or a blog users can simply save that specific web page in the form of a PDF on their device. We can implement this feature to save the pdf format of the web page which is being displaye
5 min read
Design Patterns in Android with Kotlin
Design patterns is basically a solution or blueprint for a problem that we get over and over again in programming, so they are just typical types of problems we can encounter as programmers, and these design patterns are just a good way to solve those problems, there is a lot of design pattern in an
5 min read
Why Kotlin will replace Java for Android App Development
We have a new member in our programming languages family and itâs none other than Kotlin. In Google I/O â17, they have finally announced that for android the official first class support will be given to the Kotlin. We can almost say that Kotlin is officially in for android development and java is a
4 min read
Retrofit with Kotlin Coroutine in Android
Retrofit is a type-safe http client which is used to retrieve, update and delete the data from web services. Nowadays retrofit library is popular among the developers to use the API key. The Kotlin team defines coroutines as âlightweight threadsâ. They are sort of tasks that the actual threads can e
3 min read
Android App Development with Kotlin: A Technical Overview
Android Kotlin app development is a popular way to create mobile applications for the Android platform. Kotlin is a modern programming language that is designed to be easy to use and understand, making it a great choice for developers who want to create apps quickly and efficiently. In this article,
7 min read
Flutter vs Kotlin - For Android Development
Believe it or not but the future is going to be in the hands of compact devices such as mobile phones, tablets, etc. In today's tech-driven era, every single requirement is being fulfilled with the help of smartphones, and the medium used is Mobile applications. Android development is like being a d
7 min read
Dependency Injection in Android With Koin
Koin is an efficient dependency injection framework, to whom we delegate the duty of instantiating various objects of an application. We'll explore how Koin can assist us in efficiently managing these dependencies. Begin using Koin Koin is a really simple and easy framework, all we have to do is con
4 min read
Calendar View App in Android with Kotlin
Calendar View is seen in most travel booking applications in which the user has to select the date of the journey. For the selection of the date, this view is used. In this article, we will take a look at How to implement Calendar View within our Android application using Kotlin. A sample video is g
3 min read
Why You Should Switch to Kotlin from Java to Develop Android Apps?
All the new Android developers see Java as the ideal option because of many reasons given it is age-old language, there are a lot of resources when it comes to java and also it's comfort levels are pretty high. But the time has come, we invite a change. The change is Kotlin. At Google I/O 2017, Goog
3 min read