LearnAI ToolsCareerPractice BuildsPlayContact
Lesson 4618 min read

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.Tests
cd MyApp.Tests
dotnet add reference ../MyApp/MyApp.csproj

Writing 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 test
Example Output

Click Run to see what this code prints.

Assertions

MethodChecks
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.

Core C# Complete!

You've completed all 46 core C# lessons — from fundamentals through Object-Oriented Programming, collections, LINQ, async programming, and testing. Next, you'll apply everything you've learned to build real web applications with ASP.NET Core.

Start ASP.NET Core →