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)
- Add the xUnit package:
1 2 3
dotnet add package xunit dotnet add package Microsoft.NET.Test.Sdk dotnet add package xunit.runner.visualstudio
- 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)!