Unit Testing Basics

Test your code automatically

Posted by Rodrigo Castro on January 1, 2025

Unit tests check that small parts of your code work correctly automatically.

๐Ÿงช Why Test?

  • Catch bugs early
  • Refactor safely
  • Prove your code works

๐Ÿ—๏ธ Create a Test Project

  1. In terminal, run:
    1
    2
    
     dotnet new xunit -n MyTests
     cd MyTests
    
  2. Add your code project as a reference:
    1
    
     dotnet add reference ../MyApp/MyApp.csproj
    

๐Ÿ“ Writing a Test

1
2
3
4
5
6
7
8
9
public class MathTests
{
    [Fact]
    public void Add_Works()
    {
        int result = Add(2, 3);
        Assert.Equal(5, result);
    }
}
  • [Fact]: Marks a test method
  • Assert.Equal: Checks for expected result

๐Ÿƒโ€โ™‚๏ธ Run Tests

1
dotnet test

๐Ÿ’ก Try It!

Write a function Square(int n) and a test that checks Square(4) returns 16.

1
2
3
4
5
[Fact]
public void Square_Works()
{
    Assert.Equal(16, Square(4));
}

Next: Testing with xUnit and NUnit!