Introduction
Test-Driven Development (TDD) is a programming technique that inverts the traditional order of software development. It consists of three main stages: Red, Green, and Refactor.
In the initial Red stage, a test is created that does not pass because the corresponding functionality has not been implemented yet. This is why this stage is referred to as ‘Red.’ The purpose of this stage is to define a failing test that needs to be passed.
Next comes the Green stage, where the goal is to fulfill the requirements set by the test with the simplest code possible. The focus here is on making the test pass as quickly as possible, ensuring that the functionality works as expected.
In the final phase, Refactoring, the previously written code is reviewed and improved without altering its functionality. This may involve cleaning up, organizing, and optimizing the code to make it more readable and
maintainable. The refactoring step ensures that the codebase remains clean and efficient, adhering to good coding practices.
Example
Our goal is to write a program that determines if a given number is even, returning true for even numbers and false for odd numbers. To achieve this, we will employ Test-Driven Development (TDD).
Instead of writing our implementation code first, we start by writing tests for the functionality we plan to implement. In this phase, the tests do not pass.
// C# code
public class NumberTests
{
[Fact]
public void CheckIfEvenNumber_ForEvenNumber_ReturnsTrue()
{
// Arrange
int number = 2;
// Act
var result = Number.CheckIfEvenNumber(number);
// Assert
result.Should().BeTrue();
}
[Fact]
public void CheckIfEvenNumber_ForOddNumber_ReturnsFalse()
{
// Arrange
int number = 1;
// Act
var result = Number.CheckIfEvenNumber(number);
// Assert
result.Should().BeFalse();
}
} In the next stage, we write the implementation of the `CheckIfEvenNumber` method, ensuring the code is as simple as possible to meet the test requirements.
// C# code
public class Number
{
public static bool CheckIfEvenNumber(int number)
{
if (number % 2 == 0)
{
return true;
}
else
{
return false;
}
}
} In the last stage, we should refactor the code, improving its structure without changing functionality. In this case, we have the opportunity to significantly shorten the code, making it more efficient and maintainable.
// C# code
public class Number
{
public static bool CheckIfEvenNumber(int number)
{
return (number % 2 == 0);
}
} Conclusion
Test-Driven Development (TDD) forces us to thoroughly consider the requirements before starting to code. Often, this approach enables us to identify more test cases compared to traditional software development. As a result, the application tends to be better organized and structured. Moreover, TDD provides an additional benefit during the code refactoring process: it uses existing tests to verify that the functionality is maintained, ensuring that the code continues to work as expected.

