September 3, 2026

Simple Example of Test-Driven Development(TDD) in Visual Studio C# – Step by Step Tutorial

Updated August 2026 — full tutorial restored for this URL.

This tutorial shows TDD in Visual Studio with C# and xUnit — same kata style as the JavaScript post.

JS twin: TDD in JavaScript.

  1. Create projects
  2. Red – first test
  3. Green – implement
  4. Refactor and extend
  5. Tips in Visual Studio

1. Create projects

dotnet new classlib -n StringCalc
dotnet new xunit -n StringCalc.Tests
dotnet add StringCalc.Tests reference StringCalc

Open the solution in Visual Studio; Test Explorer will discover xUnit tests.

2. Red – first test

using Xunit;

public class CalculatorTests
{
    [Fact]
    public void Empty_returns_zero()
    {
        var calc = new Calculator();
        Assert.Equal(0, calc.Add(""));
    }
}

Build — fails until Calculator exists.

3. Green – implement

public class Calculator
{
    public int Add(string numbers)
    {
        if (string.IsNullOrEmpty(numbers)) return 0;
        return 0;
    }
}

4. Refactor and extend

[Theory]
[InlineData("1", 1)]
[InlineData("1,2,3", 6)]
public void Sums_comma_separated(string input, int expected)
{
    Assert.Equal(expected, new Calculator().Add(input));
}
public int Add(string numbers)
{
    if (string.IsNullOrEmpty(numbers)) return 0;
    return numbers.Split(',').Select(int.Parse).Sum();
}

5. Tips in Visual Studio

  • Use Test Explorer → Run All after each tiny change.
  • Keep production code in the class library, tests in the test project.
  • NUnit works the same idea with [Test] / [TestCase].

Kindson Munonye

Kindson Munonye is a software engineer and technical author covering machine learning, statistics, REST APIs, Python, and software engineering. He publishes free tutorials on The Genius Blog and live classes on Alkademy. GitHub · LinkedIn · About · Alkademy

View all posts by Kindson Munonye →
0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted