Sign in
Log inSign up
The Red Green Refactor of TDD

The Red Green Refactor of TDD

Kagiri's photo
Kagiri
·Sep 24, 2021·

2 min read

Introduction

Test-Driven Development is a software engineering approach that ensures that you write the tests for the SUT (system under test) before or maybe even after writing the actual production code implementation. While starting off with TDD, you may have come across the term Red Green Refactor and wondered what it meant. Well, this is the base method that is usually at play when practicing TDD.

Red:

For any unimplemented feature or method of any sort that isn't already covered by a test case, you have to first of all write it's failing test. To do this, make sure it fails by only writing the least code possible to make it compile. Do not go for implementation right away. Compile the code and see it fail. Say you have set up your test as shown in the figure below,

val truePassWord = "test123"
    val ourPassWord = getPassword(truePassWord)

    if(truePassWord == ourPassWord){
       println("Nice..The password matches")
    }else{
        println("Wrong password!!")
    }

and your function / method is set like so,

fun getPassword(passCode:String):String{
    return " "
}

The test will fail because we are returning an empty string rather than the one passed in as desired.

Green:

At this stage, you now rectify whatever was making the code to fail during the red stage. You provide the implementation to make the test to pass. You don't have to be so clinical at this point with the implementations instead just provide the cheapest way to make that test pass. Run the test once more and see it has passed.

So we provide a fix for the function above like below

fun getPassword(passCode:String):String{
    val name = passCode
    return name
}

Refactor:

Now that your test is a green test, you are at liberty to modify the solution you provided earlier and make it simpler, shorter, legible and more understandable. As long as your test remains green, you haven't broken the code and it's okay.

Now we can do something simple such as

fun getPassword(passCode:String):String{
    return passCode
}

Conclusion

You write the tests first and make sure they are failing and then provide the right implementations for whatever you are testing then you can do a clean up for the implementation later on.