Automated Unit Testing

Ensure code quality with unit tests

Posted by Rodrigo Castro on February 15, 2025

Automated unit testing ensures your code works as intended and helps prevent bugs.

๐Ÿงช What is a Unit Test?

A unit test checks one small part (unit) of your code (usually a method) independently from the rest.

๐Ÿ—๏ธ Setting Up (xUnit Example)

  1. Add the xUnit package:
    1
    2
    3
    
    dotnet add package xunit
    dotnet add package Microsoft.NET.Test.Sdk
    dotnet add package xunit.runner.visualstudio
    
  2. Create a test project:
    1
    
    dotnet new xunit -n MyProject.Tests
    

โœ๏ธ Writing a Test

1
2
3
4
5
6
7
8
9
10
public class CalculatorTests
{
    [Fact]
    public void Add_ReturnsSum()
    {
        var calc = new Calculator();
        var result = calc.Add(2, 3);
        Assert.Equal(5, result);
    }
}

๐Ÿšฆ Running Tests

1
dotnet test

๐Ÿ’ก Tips

  • Write tests for all important logic.
  • Use test runners in Visual Studio, Rider, or VS Code for convenience.

Next: Behavior-Driven Development (BDD)!