Unit Testing Basics
Learn how to write and run unit tests for C# code using xUnit, one of the most popular .NET testing frameworks.
Why Unit Test?
A unit test verifies that a small piece of code (usually a single method) behaves correctly, automatically and repeatably — catching regressions before they reach production.
Setting Up xUnit
xUnit is one of the most popular .NET testing frameworks. Create a dedicated test project alongside your main project:
dotnet new xunit -o MyApp.Testscd MyApp.Testsdotnet add reference ../MyApp/MyApp.csprojWriting a Test
public class Calculator{ public int Add(int a, int b) => a + b;}
public class CalculatorTests{ [Fact] public void Add_ReturnsSumOfTwoNumbers() { var calculator = new Calculator();
int result = calculator.Add(2, 3);
Assert.Equal(5, result); }}Running tests
dotnet testExample Output
Click Run to see what this code prints.
Assertions
| Method | Checks |
|---|---|
| Assert.Equal(expected, actual) | Two values are equal |
| Assert.True(condition) | A condition is true |
| Assert.Throws<T>(action) | An action throws a specific exception |
| Assert.Null(value) | A value is null |
Theory for Multiple Cases
Use `[Theory]` with `[InlineData(...)]` to run the same test logic against multiple sets of inputs, instead of copy-pasting near-identical [Fact] tests.
FAQs
No — NUnit and MSTest are also widely used. xUnit is currently the most common choice for new ASP.NET Core projects.
Summary
- Unit tests verify small pieces of code automatically and repeatably.
- [Fact] tests a single case; [Theory] with [InlineData] tests multiple cases.
- Assert methods check expected outcomes and fail the test if they don't hold.