TDD – Test Driven Development

TDD – Test Driven Development

Introduction

Creating a simple calculator class using Test-Driven Development (TDD) in C# involves following the TDD cycle: write a failing test, write just enough code to make the test pass, and then refactor the code.

For this example, we’ll use NUnit as our testing framework and Moq, although Moq may not be necessary for a simple calculator class as it doesn’t typically involve dependencies that need mocking.

However, I’ll show where it could be used in a more complex scenario.

Step 1: Set Up the Project Environment

Create a C# Project: Start by creating a new C# project. This can be a class library project as you’re building a simple calculator class.

Add NUnit and Moq: Add NUnit to your project as the testing framework, and Moq for mocking dependencies (if needed). You can add these via NuGet package manager.

Install-Package NUnit 
Install-Package Moq

Create Test and Implementation Classes: Create two classes, CalculatorTests for your tests and Calculator for the implementation.

Step 2: Write Your First Test

Start with a simple functionality, like adding two numbers.

Write a Failing Test: In your CalculatorTests class, write a test for adding two numbers.

using NUnit.Framework;
using YourNamespace; // Replace with the actual namespace of your Calculator class

[TestFixture]
public class CalculatorTests
{
    [Test]
    public void Add_TwoNumbers_ReturnsSum()
    {
        // Arrange
        var calculator = new Calculator();

        // Act
        var result = calculator.Add(1, 2);

        // Assert
        Assert.AreEqual(3, result);
    }
}

This test will fail because Calculator.Add doesn’t exist yet. In fact, it won’t even build until you create a class and add an appropriate method.

Step 3: Implement the Feature to Pass the Test

Write Enough Code to Pass the Test: Create the Calculator class and implement the Add method.

namespace YourNamespace
{
    public class Calculator
    {
        public int Add(int a, int b)
        {
            return a + b; // Simple implementation to pass the test
        }
    }
}

Run the Test: Run the test again. It should pass this time.

Step 4: Refactor and Repeat

With your test passing, refactor if necessary. Then, repeat this process for other operations (subtract, multiply, divide).

Adding More Tests

Subtraction Test: Add a test for subtraction.

[Test]
public void Subtract_TwoNumbers_ReturnsDifference()
{
    // Arrange...
    // Act...
    // Assert...
}

Implement Subtraction: Implement the subtraction feature in Calculator.

Continue for Multiply and Divide: Follow the same process for multiplication and division.

Advanced Scenario: Using Moq (If Necessary)

In a more complex scenario where Calculator depends on an external service or repository, you might use Moq to mock these dependencies. For instance, if Calculator uses a ILogger interface to log operations:

Mocking ILogger: In your test class, create a mock of ILogger.

private Mock<ILogger> _mockLogger;

[SetUp]
public void SetUp()
{
    _mockLogger = new Mock<ILogger>();
}

Using Mock in Tests: Pass the mock object to the Calculator constructor and set up expectations or verify interactions.

[Test]
public void Add_TwoNumbers_LogsMessage()
{
    // Arrange...
    var calculator = new Calculator(_mockLogger.Object);

    // Act...
    // Assert...
    _mockLogger.Verify(logger => logger.Log("Add operation performed"), Times.Once);
}

Conclusion

TDD is a powerful methodology for building robust applications. By writing your tests first and only writing enough code to pass these tests, you can ensure your application is well-tested and adheres to the requirements.

In this example, we’ve seen how to apply TDD to create a simple calculator class in C#, using NUnit for testing and Moq for mocking (when needed).

As you grow more comfortable with TDD, you can apply this approach to more complex problems and larger applications.

You can find the official documentation for NUnit here: – https://docs.nunit.org/articles/nunit/intro.html

Also, there is a great video on TDD here: – https://www.youtube.com/watch?v=y8TcPr73Bwo

Stephen

Hi, my name is Stephen Finchett. I have been a software engineer for over 30 years and worked on complex, business critical, multi-user systems for all of my career. For the last 15 years, I have been concentrating on web based solutions using the Microsoft Stack including ASP.Net, C#, TypeScript, SQL Server and running everything at scale within Kubernetes.