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
- In terminal, run:
1 2
dotnet new xunit -n MyTests cd MyTests
- 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 methodAssert.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!