.NET Unit Testing with xUnit Tutorial
On this page
Learning Objective
Write clear, deterministic unit tests with xUnit using arrange, act and assert, choose between fakes and mocks sensibly, control time with FakeTimeProvider, build test data with builders, cover security-relevant logic with hostile inputs, and pick assertion and mocking libraries with an eye on licensing and maintenance.
Concept Explanation
A good unit test is small, fast, independent, and readable enough to serve as documentation. The classic structure is arrange, act, assert: set up the object under test and its inputs, perform one action, then check the outcome. Name tests after behavior, such as Cannot_skip_from_todo_to_done, so a failing test name explains the problem without opening the file. xUnit, the de facto .NET framework, creates a new instance of the test class for each test, which gives isolation by default, and offers Fact for a single case and Theory with InlineData, MemberData, or ClassData for running the same test over many inputs. The newest major version, xUnit v3, is built on the Microsoft Testing Platform and improves tooling support and parallelism.
The difference between test doubles matters more than the library you use. A fake is a working lightweight implementation, such as an in-memory store, that you can inspect afterward. A stub returns canned answers. A mock verifies that certain calls happened. Overusing mocks produces tests that mirror the implementation line by line, so refactoring breaks them even though behavior is unchanged. Prefer fakes and state-based assertions, checking what the code did to its collaborators' data rather than which methods it called, and reserve mocks for interactions that are the point, such as an email being sent exactly once. NSubstitute offers a friendly syntax for the cases you do need. The Moq library saw a controversy in 2023 when a release added a sponsorship check that sent hashed email addresses, which led many teams to reconsider it, a useful reminder to review what your test dependencies actually do.
Two other test dependencies changed licensing recently. FluentAssertions moved to a commercial license with version 8 in early 2025, and teams commonly moved to alternatives such as Shouldly or the AwesomeAssertions fork, or simply to xUnit's built-in Assert methods, which are perfectly adequate. Whatever you choose, keep production code free of test libraries and pin versions. Control the two main sources of nondeterminism: time and randomness. The FakeTimeProvider from Microsoft.Extensions.TimeProvider.Testing lets you set and advance the clock, so tests of expiry, deadlines, and token lifetimes are exact and instant. Inject random number sources or seed them.
Test data deserves as much design as production code. Repeating twelve lines of setup in every test hides what each one is about. A builder provides valid defaults and lets a test override only what matters to it, so the interesting detail stands out. Libraries such as Bogus generate realistic fake data. For inputs, table-driven theories are ideal for security logic: a validator or sanitizer should be run against a list of hostile strings, oversized values, Unicode tricks, and boundary numbers, each a one-line addition. Property-based testing with FsCheck goes further by generating inputs and checking invariants, such as a parsed then formatted value round-tripping. Together they turn unknowns into a growing, executable list of attacks and edge cases.
| Concept | Guidance | Reason |
|---|---|---|
| Structure | Arrange, act, assert, one behavior per test | Readable, precise failures |
| Naming | Describe the behavior, not the method | Failure names document the bug |
| Fake versus mock | Prefer fakes and state assertions | Less coupling to implementation |
| Time | Inject TimeProvider, use FakeTimeProvider | Deterministic, instant expiry tests |
| Data | Builders with valid defaults | Each test shows only what matters |
| Hostile input | Theories over attack strings and boundaries | Cheap, growing security coverage |
Worked Example: Domain Tests, a Handler Test with a Fake, Time Control and an Attack-String Theory
The tests below show xUnit patterns for a state machine, an expiring invitation with a fake clock, a service tested with a fake store, and a validator exercised with hostile inputs.
public class TaskItemTests
{
private static readonly DateTimeOffset Now = new(2026, 9, 1, 9, 0, 0, TimeSpan.Zero);
[Theory]
[InlineData(TaskState.Todo, TaskState.Done)]
[InlineData(TaskState.Todo, TaskState.Review)]
[InlineData(TaskState.Done, TaskState.Todo)]
[InlineData(TaskState.Done, TaskState.InProgress)]
public void Illegal_transitions_are_rejected(TaskState from, TaskState to)
{
var task = new TaskBuilder().InState(from).Build();
var result = task.MoveTo(to, Now);
Assert.False(result.IsSuccess);
Assert.Equal("task.transition", result.Error!.Code);
Assert.Equal(from, task.State); // state unchanged after a rejected move
}
[Fact]
public void Completing_a_task_records_the_time_and_reopening_clears_it()
{
var task = new TaskBuilder().InState(TaskState.Review).Build();
task.MoveTo(TaskState.Done, Now);
Assert.Equal(Now, task.CompletedAt);
}
}
public class InvitationTests
{
[Fact]
public void An_invitation_expires_after_seven_days_exactly()
{
var clock = new FakeTimeProvider(new DateTimeOffset(2026, 9, 1, 0, 0, 0, TimeSpan.Zero));
var invitation = Invitation.Create("a@b.com", clock.GetUtcNow(), TimeSpan.FromDays(7));
clock.Advance(TimeSpan.FromDays(7) - TimeSpan.FromSeconds(1));
Assert.True(invitation.IsValid(clock.GetUtcNow()));
clock.Advance(TimeSpan.FromSeconds(2)); // now past the deadline, no waiting involved
Assert.False(invitation.IsValid(clock.GetUtcNow()));
}
}// A fake beats a mock here: assert on the resulting state, not on which methods were called.
public sealed class FakeNoteStore : INoteStore
{
public List<NoteEntity> Saved { get; } = [];
public Task AddAsync(NoteEntity n, CancellationToken ct) { Saved.Add(n); return Task.CompletedTask; }
/* other members ... */
}
public class CreateNoteHandlerTests
{
[Fact]
public async Task Titles_are_trimmed_and_saved_with_the_current_owner()
{
var store = new FakeNoteStore();
var handler = new CreateNoteHandler(store, new FakeCurrentUser("alice"), TimeProvider.System);
await handler.HandleAsync(new CreateNote(" Plan the sprint ", null), default);
var saved = Assert.Single(store.Saved);
Assert.Equal("Plan the sprint", saved.Title);
Assert.Equal("alice", saved.OwnerId); // owner comes from the identity, not the request
}
[Fact]
public async Task An_email_is_sent_exactly_once() // a mock is appropriate: the interaction is the requirement
{
var mailer = Substitute.For<IEmailSender>();
await new InviteHandler(mailer /* ... */).HandleAsync(new Invite("x@y.com"), default);
await mailer.Received(1).SendAsync(Arg.Is<Email>(e => e.To == "x@y.com"), Arg.Any<CancellationToken>());
}
}// Hostile input as data: adding a new attack string is a one-line change.
public class NoteTitleValidatorTests
{
private readonly CreateNoteValidator _validator = new();
[Theory]
[InlineData("")]
[InlineData(" ")]
[InlineData("\u0000")] // null byte
[InlineData("A\r\nInjected: header")] // control characters and header-style injection
public void Blank_or_control_character_titles_are_invalid(string title) =>
Assert.False(_validator.Validate(new CreateNote(title, null)).IsValid);
[Fact] public void A_title_of_201_characters_is_invalid() =>
Assert.False(_validator.Validate(new CreateNote(new string('x', 201), null)).IsValid);
[Fact] public void A_title_of_exactly_200_characters_is_valid() =>
Assert.True(_validator.Validate(new CreateNote(new string('x', 200), null)).IsValid);
[Theory]
[InlineData("<script>alert(1)</script>")]
[InlineData("'; DROP TABLE Notes;--")]
public void Markup_and_sql_are_accepted_as_plain_text_and_never_interpreted(string title) =>
Assert.True(_validator.Validate(new CreateNote(title, null)).IsValid); // stored verbatim, escaped on output, parameterized in SQL
}// A builder keeps setup short and states only what a test cares about.
public sealed class TaskBuilder
{
private string _title = "Write report"; private TaskState _state = TaskState.Todo; private Guid? _assignee;
public TaskBuilder InState(TaskState s) { _state = s; return this; }
public TaskBuilder AssignedTo(Guid id) { _assignee = id; return this; }
public TaskItem Build()
{
var task = TaskItem.Create(_title).Value!;
foreach (var step in PathTo(_state)) task.MoveTo(step, DateTimeOffset.UnixEpoch); // reach the state legitimately
if (_assignee is { } a) task.Assign(a);
return task;
}
private static IEnumerable<TaskState> PathTo(TaskState s) => Enum.GetValues<TaskState>().Where(x => x != TaskState.Todo && x <= s);
}The last theory documents an important design decision as an executable fact: the validator does not try to strip markup or SQL characters, because encoding on output and parameterization in queries are the right defenses, and the test guards against someone adding a fragile denylist.
Real-World Examples
- In August 2023 the Moq library released a version that included a SponsorLink component that sent a hash of the developer's email address to a remote service during builds, prompting widespread backlash over privacy and build-time behavior. The maintainer reverted the change, but the episode led many teams to audit test dependencies and to prefer alternatives like NSubstitute or hand-written fakes.
- In January 2025 FluentAssertions version 8 introduced a commercial license for many users, ending the assumption that the popular assertion library would remain free, and the community responded with forks such as AwesomeAssertions and a move toward Shouldly or plain xUnit assertions. It reinforced the practice of keeping test code simple enough that swapping a library is inexpensive.
Review Questions & Answers
A fake lets you assert on the resulting state, for instance that a trimmed title was saved with the right owner, which survives refactoring because the test does not depend on which methods were called or in what order. A mock ties the test to the implementation's interactions, so harmless internal changes break it without any change in behavior.
The test controls the clock directly, advancing it by exact amounts, so you can check the instant before and after a deadline without sleeping or depending on the real time. Tests become instant and deterministic, and edge cases such as the boundary second are easy to verify.
It makes the growing list of known hostile inputs and boundary values executable documentation. Each new attack pattern or bug report becomes a single additional line, and the theory ensures the validator keeps handling all of them, preventing regressions and documenting deliberate decisions such as accepting markup as plain text.
Test libraries run inside your build and on developer machines, so a change in license terms can create legal obligations, and a change in behavior, such as sending data during builds, can create privacy or supply chain risk. Pinning versions, reviewing updates, and keeping tests simple enough to replace dependencies limits that exposure.