Open In App

Working with Test Driven Development(TDD) in Android with Kotlin

Last Updated : 14 May, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

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:

  1. In the Project view, navigate to the directory that contains your test file(s).
  2. Right-click on the file you want to run and select “Run ‘Tests in …'” from the context menu.
  3. 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.



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads