Chapter 1: Introduction to Testing .NET Applications
What You Will Learn
Map the testing pyramid to .NET 10 application architecture, identifying where unit, integration, and end-to-end tests deliver value versus maintenance cost.
Describe the ParcelPilot domain model and explain how its entities (Shipment, Parcel, Address, TrackingEvent) flow through layered architecture boundaries.
Recognize architectural seams (repositories, gateways, UI components) that require abstraction to achieve deterministic, repeatable tests.
Distinguish between testable design (an architectural property) and test-driven design (a workflow methodology).
Identify determinism risks in .NET code, including static dependencies on time, randomness, HTTP clients, and persistence mechanisms.
Prerequisites
No additional prerequisites beyond those listed in About This Book.
Concept Overview
Professional .NET development requires more than manual verification. As systems grow, regression costs increase non-linearly. Automated testing provides a safety net, enables refactoring, documents system behavior, and shortens the feedback loop between code changes and defect discovery.
This book uses ParcelPilot, a parcel shipping and tracking platform, as its consistent reference application. ParcelPilot handles shipment creation, label purchases, tracking events, and delivery exceptions through an ASP.NET Core API and a Blazor admin interface. Its domain includes shipments, parcels, addresses, tracking events, and carrier integrations. These entities move through distinct architectural layers: Domain (business rules), Application (orchestration), Infrastructure (persistence and external services), API (HTTP endpoints), and Blazor (UI components).
The testing pyramid provides a framework for distributing test effort. Unit tests form the base. They verify isolated business rules in milliseconds without external dependencies. Integration tests occupy the middle layer. They validate component interactions, such as API endpoints hosted in memory or repositories communicating with real databases. End-to-end tests sit at the apex. They exercise complete user flows through browser automation.
Each layer trades execution speed for confidence. Unit tests run thousands per minute but cannot detect wiring errors. End-to-end tests catch integration failures but execute slowly and flake under timing variations. In production, I have seen teams abandon test suites because they could not trust the results.
Determinism separates reliable tests from fragile ones. A deterministic test produces identical results across executions, environments, and machines. Non-deterministic tests fail intermittently due to race conditions, network latency, or data left behind by previous runs. In ParcelPilot, determinism requires controlling the system clock (to avoid DateTime.Now variations), replacing HTTP clients with test doubles (to avoid external carrier APIs), and managing database state (to prevent test pollution).
Flaky tests destroy trust in the entire suite.
Testable design differs from test-driven design. Structuring code so tests can exercise it without heroic effort requires dependency injection, explicit boundaries, and avoiding static state. Test-driven design is a workflow where tests precede implementation. Writing testable code does not require TDD. However, effective TDD requires testable design. This book emphasizes testable architecture first, then applies TDD workflows in later chapters.
Architecture enables testing.
The testing stack for ParcelPilot includes xUnit as the primary unit testing framework, with NUnit comparisons where framework differences matter. Moq and NSubstitute provide mocking capabilities. WebApplicationFactory hosts the API for integration tests. These tools support the architectural goal: fast, deterministic feedback that respects layer boundaries.
Step-by-Step Implementation
Step 1: Define Core Domain Entities
ParcelPilot's domain model centers on shipments and their lifecycle. Start with immutable records for value objects and entities. Immutability reduces side effects and simplifies assertions. Using records for entities is a teaching simplification; Chapter 4 will evolve these toward full entity semantics as we introduce behavior and identity concerns.
Define the Address Record
Define the Address record first. It represents locations for senders and recipients.
namespace ParcelPilot.Domain.Entities;
public record Address(
string Street,
string City,
string State,
string PostalCode,
string Country);
Define the ShipmentStatus Enumeration
Define the ShipmentStatus enumeration. It tracks the parcel lifecycle from creation through delivery or failure.
Define the Parcel record. A shipment contains one or more parcels, each with weight and declared value.
namespace ParcelPilot.Domain.Entities;
public record Parcel(
Guid Id,
decimal WeightInKilograms,
decimal DeclaredValue);
Define the TrackingEvent Record
Define the TrackingEvent record. It captures status changes and location updates throughout a shipment's journey.
namespace ParcelPilot.Domain.Entities;
public record TrackingEvent(
Guid Id,
string CarrierTrackingNumber,
ShipmentStatus Status,
string Location,
DateTime Timestamp,
string Description);
Define the Shipment Aggregate
Finally, define the Shipment aggregate root. It composes the other types and carries the tracking number and status.
namespace ParcelPilot.Domain.Entities;
public record Shipment(
Guid Id,
string TrackingNumber,
Address Sender,
Address Recipient,
IReadOnlyList<Parcel> Parcels,
ShipmentStatus Status,
DateTime CreatedAt);
These records form the data under test. They contain no behavior yet, but their structure dictates how the application processes shipping logic.
Step 2: Define Repository Abstractions
Application services should not depend directly on Entity Framework Core. They depend on abstractions. Define IShipmentRepository to represent the persistence boundary for shipments. This minimal interface omits broader query responsibilities intentionally; we will extend it in Chapter 8.
These interfaces reside in the Domain project. They contain no EF Core references. The Infrastructure project will provide implementations using DbContext. Tests will provide fake implementations or use in-memory databases. The abstractions ensure that unit tests of business logic never accidentally trigger database round-trips.
Step 3: Define the External Gateway Abstraction
ParcelPilot integrates with external carriers for label purchases and tracking updates. These HTTP calls must not execute during unit tests. Define ICarrierGateway to abstract the network boundary.
using ParcelPilot.Domain.Entities;
namespace ParcelPilot.Domain.Interfaces;
public record LabelPurchaseResult(
string LabelUrl,
decimal Cost,
string CarrierTrackingNumber);
public record TrackingEventDto(
DateTime Timestamp,
string Location,
string Description);
public interface ICarrierGateway
{
Task<LabelPurchaseResult> PurchaseLabelAsync(Shipment shipment, CancellationToken cancellationToken = default);
Task<IReadOnlyList<TrackingEventDto>> GetTrackingEventsAsync(string carrierTrackingNumber, CancellationToken cancellationToken = default);
}
The gateway returns data transfer objects, not domain entities. This prevents external schema changes from rippling into the domain model. Unit tests will mock this interface to simulate carrier responses without network access.
Step 4: Implement the Application Service
With abstractions defined, implement ShipmentService in the Application layer. This service orchestrates domain logic, persistence, and external calls.
using ParcelPilot.Domain.Entities;
using ParcelPilot.Domain.Interfaces;
namespace ParcelPilot.Application.Services;
public class ShipmentService
{
private readonly IShipmentRepository _repository;
private readonly ICarrierGateway _gateway;
public ShipmentService(IShipmentRepository repository, ICarrierGateway gateway)
{
_repository = repository ?? throw new ArgumentNullException(nameof(repository));
_gateway = gateway ?? throw new ArgumentNullException(nameof(gateway));
}
public async Task<Shipment> CreateShipmentAsync(
Address sender,
Address recipient,
IReadOnlyList<Parcel> parcels,
CancellationToken cancellationToken = default)
{
if (parcels.Count == 0)
{
throw new ArgumentException("Shipment must contain at least one parcel.", nameof(parcels));
}
// Note: The following dependencies are non-deterministic and temporary.
// Chapter 4 will refactor these to injectable abstractions for testability.
var trackingNumber = GenerateTrackingNumber();
var shipment = new Shipment(
Id: Guid.NewGuid(),
TrackingNumber: trackingNumber,
Sender: sender,
Recipient: recipient,
Parcels: parcels,
Status: ShipmentStatus.Created,
CreatedAt: DateTime.UtcNow);
await _repository.AddAsync(shipment, cancellationToken);
await _repository.SaveChangesAsync(cancellationToken);
return shipment;
}
public async Task PurchaseLabelAsync(
string trackingNumber,
CancellationToken cancellationToken = default)
{
var shipment = await _repository.GetByTrackingNumberAsync(trackingNumber, cancellationToken);
if (shipment is null)
{
throw new InvalidOperationException($"Shipment {trackingNumber} not found.");
}
var result = await _gateway.PurchaseLabelAsync(shipment, cancellationToken);
// Domain logic would record the purchase here
}
private static string GenerateTrackingNumber()
{
// Note: This is non-deterministic and will be refactored in Chapter 4.
return $"PP-{Guid.NewGuid().ToString("N")[..8].ToUpper()}";
}
}
The service receives dependencies through its constructor. It coordinates between the repository and gateway without knowing their concrete implementations. This structure enables unit tests to substitute test doubles for both dependencies.
Full Example
The following code consolidates the domain model, abstractions, and service into a cohesive structure. It represents the foundation upon which subsequent chapters build the ParcelPilot test suite.
// Domain/Entities/Address.cs
namespace ParcelPilot.Domain.Entities;
public record Address(
string Street,
string City,
string State,
string PostalCode,
string Country);
// Domain/Entities/ShipmentStatus.cs
namespace ParcelPilot.Domain.Entities;
public enum ShipmentStatus
{
Created,
PickedUp,
InTransit,
OutForDelivery,
Delivered,
FailedDelivery
}
// Domain/Entities/Parcel.cs
namespace ParcelPilot.Domain.Entities;
public record Parcel(
Guid Id,
decimal WeightInKilograms,
decimal DeclaredValue);
// Domain/Entities/TrackingEvent.cs
namespace ParcelPilot.Domain.Entities;
public record TrackingEvent(
Guid Id,
string CarrierTrackingNumber,
ShipmentStatus Status,
string Location,
DateTime Timestamp,
string Description);
// Domain/Entities/Shipment.cs
namespace ParcelPilot.Domain.Entities;
public record Shipment(
Guid Id,
string TrackingNumber,
Address Sender,
Address Recipient,
IReadOnlyList<Parcel> Parcels,
ShipmentStatus Status,
DateTime CreatedAt);
// Domain/Interfaces/IShipmentRepository.cs
using ParcelPilot.Domain.Entities;
namespace ParcelPilot.Domain.Interfaces;
public interface IShipmentRepository
{
Task<Shipment?> GetByTrackingNumberAsync(string trackingNumber, CancellationToken cancellationToken = default);
Task AddAsync(Shipment shipment, CancellationToken cancellationToken = default);
Task SaveChangesAsync(CancellationToken cancellationToken = default);
}
// Domain/Interfaces/ITrackingRepository.cs
using ParcelPilot.Domain.Entities;
namespace ParcelPilot.Domain.Interfaces;
public interface ITrackingRepository
{
Task<IReadOnlyList<TrackingEvent>> GetByTrackingNumberAsync(string trackingNumber, CancellationToken cancellationToken = default);
Task AddAsync(TrackingEvent trackingEvent, CancellationToken cancellationToken = default);
}
// Domain/Interfaces/ICarrierGateway.cs
using ParcelPilot.Domain.Entities;
namespace ParcelPilot.Domain.Interfaces;
public record LabelPurchaseResult(
string LabelUrl,
decimal Cost,
string CarrierTrackingNumber);
public record TrackingEventDto(
DateTime Timestamp,
string Location,
string Description);
public interface ICarrierGateway
{
Task<LabelPurchaseResult> PurchaseLabelAsync(Shipment shipment, CancellationToken cancellationToken = default);
Task<IReadOnlyList<TrackingEventDto>> GetTrackingEventsAsync(string carrierTrackingNumber, CancellationToken cancellationToken = default);
}
// Application/Services/ShipmentService.cs
using ParcelPilot.Domain.Entities;
using ParcelPilot.Domain.Interfaces;
namespace ParcelPilot.Application.Services;
public class ShipmentService
{
private readonly IShipmentRepository _repository;
private readonly ICarrierGateway _gateway;
public ShipmentService(IShipmentRepository repository, ICarrierGateway gateway)
{
_repository = repository ?? throw new ArgumentNullException(nameof(repository));
_gateway = gateway ?? throw new ArgumentNullException(nameof(gateway));
}
public async Task<Shipment> CreateShipmentAsync(
Address sender,
Address recipient,
IReadOnlyList<Parcel> parcels,
CancellationToken cancellationToken = default)
{
if (parcels.Count == 0)
{
throw new ArgumentException("Shipment must contain at least one parcel.", nameof(parcels));
}
var trackingNumber = GenerateTrackingNumber();
var shipment = new Shipment(
Id: Guid.NewGuid(),
TrackingNumber: trackingNumber,
Sender: sender,
Recipient: recipient,
Parcels: parcels,
Status: ShipmentStatus.Created,
CreatedAt: DateTime.UtcNow);
await _repository.AddAsync(shipment, cancellationToken);
await _repository.SaveChangesAsync(cancellationToken);
return shipment;
}
public async Task PurchaseLabelAsync(
string trackingNumber,
CancellationToken cancellationToken = default)
{
var shipment = await _repository.GetByTrackingNumberAsync(trackingNumber, cancellationToken);
if (shipment is null)
{
throw new InvalidOperationException($"Shipment {trackingNumber} not found.");
}
var result = await _gateway.PurchaseLabelAsync(shipment, cancellationToken);
}
private static string GenerateTrackingNumber()
{
return $"PP-{Guid.NewGuid().ToString("N")[..8].ToUpper()}";
}
}
This structure demonstrates the separation of concerns that makes testing feasible. The Domain project contains entities and repository interfaces. The Application project contains services that coordinate these abstractions. Neither project references ASP.NET Core or Entity Framework Core directly. This isolation allows unit tests to run against the Application and Domain layers without web servers or databases.
Clean boundaries make fast tests possible.
Common Mistakes
Testing implementation details instead of behavior. Developers often write tests that verify a method called SaveChanges exactly once, or that a specific private field was set. These tests break during refactoring even when behavior remains correct. Test observable outcomes, not internal mechanics.
Testable design is not test-driven design. Teams sometimes believe they must write tests first to have testable code. This is false. Testable design results from architectural decisions (dependency injection, explicit boundaries) regardless of when tests are written. TDD is a valuable workflow, but it is not the only path to testable code.
Match test type to risk. Testing every API endpoint through browser automation produces slow, brittle suites. Testing pure business logic through integration tests with real databases wastes execution time. Match the test type to the risk: unit tests for business rules, integration tests for wiring, end-to-end tests for critical user journeys.
Non-deterministic dependencies indicate missing abstractions. Using DateTime.Now, Guid.NewGuid(), or Random directly in business logic creates tests that fail intermittently or cannot assert specific values. Static access to these dependencies prevents test isolation.
Framework details belong in infrastructure. When DbContext or HttpClient appears in application services, tests must include database configurations or network mocks. Keep framework dependencies in Infrastructure and API projects only.
Test data requires isolation. Tests that share database instances or depend on specific record IDs left by previous tests create ordering dependencies. Each test should establish its own preconditions and clean up afterward, or use isolated transactions.
Performance and Production Considerations
Test suite performance directly impacts developer productivity. Slow tests discourage execution. Developers bypass pre-commit hooks when feedback takes minutes rather than seconds.
Speed matters.
Unit tests for ParcelPilot's domain logic should execute in milliseconds. They require no containerization, database migrations, or network sockets. Keep them in a separate project from integration tests so developers can run the fast suite continuously while coding.
Integration tests using WebApplicationFactory spin up the ASP.NET Core pipeline in memory. This adds overhead. Minimize these to scenarios verifying routing, middleware, and dependency injection configuration. Do not use integration tests to exhaustively test business rule permutations; that is the domain of unit tests.
Database-backed integration tests require strategy. Each test should run inside a transaction that rolls back on completion, or use a fresh database instance per test class. The transactional approach offers speed but demands careful async handling. Fresh instances run slower yet eliminate shared state completely. Chapter 9 explores these patterns for ParcelPilot's EF Core repositories.
Choose based on your tolerance for shared state.
Parallel execution complicates determinism. xUnit runs tests in parallel by default. Static state, file system access, or shared database connections cause race conditions. When reviewing this pattern across codebases, the most common mistake was assuming static caches were safe for parallel execution. Design tests to be thread-isolated. Use unique identifiers per test, or avoid shared mutable resources entirely.
Summary
Testing .NET applications requires architectural discipline beyond framework knowledge. ParcelPilot demonstrates how layered architecture creates natural test boundaries. The testing pyramid guides investment: unit tests for business logic, integration tests for component interaction, end-to-end tests for critical flows.
Determinism remains the primary quality attribute for reliable tests. Control time, external HTTP calls, and persistence through abstractions like IShipmentRepository and ICarrierGateway. Avoid static dependencies that introduce variability between executions.
Testable design enables testing regardless of methodology. Dependency injection and explicit boundaries allow tests to substitute doubles for expensive dependencies. This foundation supports both test-after and test-driven workflows.
The entities and services defined in this chapter provide the substrate for subsequent chapters. You will write unit tests against these types, mock their dependencies, and host them in integration test pipelines. These patterns, immutability, abstraction, and layer separation, will recur throughout the book as ParcelPilot grows.
Key Terms
Testing pyramid: A model advocating a wide base of fast unit tests, a smaller middle layer of integration tests, and minimal end-to-end tests at the top.
Determinism: The guarantee that a test produces identical results across executions, environments, and machines without timing or state variations.
Testable design: An architectural approach using dependency injection and explicit boundaries to enable testing without heroic effort.
Test-driven design (TDD): A workflow where tests precede implementation, requiring testable design as a prerequisite.
Architectural seam: A boundary where behavior can be altered without modifying source code, typically via interfaces or abstract classes.
Repository pattern: An abstraction mediating between domain and data mapping layers, keeping the domain persistence-ignorant.
Gateway pattern: An abstraction encapsulating access to external systems such as HTTP APIs or third-party carriers.
Aggregate root: A domain entity serving as the entry point for a cluster of associated objects, maintaining consistency boundaries.
Mini Quiz
Which layer of the testing pyramid provides the fastest feedback but cannot detect wiring errors between components?
A. End-to-end tests
B. Integration tests
C. Unit tests
D. Load tests
In the ParcelPilot architecture, why does ShipmentService depend on IShipmentRepository rather than DbContext directly?
A. To improve database query performance
B. To allow the domain layer to remain persistence-ignorant and enable test substitution
C. To support multiple database providers simultaneously
D. To reduce memory usage in the application layer
What is the primary distinction between testable design and test-driven design?
A. Testable design requires interfaces; TDD requires abstract classes
B. Testable design is an architectural property; TDD is a workflow methodology
C. Testable design applies only to unit tests; TDD applies to integration tests
D. Testable design eliminates the need for mocks; TDD requires them
Which of the following practices most directly compromises test determinism?
A. Using constructor injection for dependencies
B. Calling DateTime.UtcNow directly within business logic
C. Implementing the repository pattern
D. Running tests in parallel with xUnit
When testing ParcelPilot's ShipmentService, why should ICarrierGateway be replaced with a test double rather than calling the actual carrier API?
A. To reduce costs associated with label purchases during testing
B. To avoid network latency and ensure deterministic, fast test execution
C. Because the carrier API does not support async/await patterns
D. To bypass authentication requirements in the development environment
Answers are provided in the Answer Key at the end of the book.
Activity
Extend the ParcelPilot domain model to support tracking events by implementing the TrackingEvent entity and its repository abstraction within your existing solution.
Open the ParcelPilot solution in Visual Studio. You'll work within the ParcelPilot.Domain project.
In Solution Explorer, right-click the Entities folder and select Add > Class. Name it TrackingEvent.cs and implement it as a record. Include the ShipmentStatus enum in the same file:
namespace ParcelPilot.Domain.Entities;
public enum ShipmentStatus
{
Created,
PickedUp,
InTransit,
OutForDelivery,
Delivered,
FailedDelivery
}
public record TrackingEvent
{
public Guid Id { get; init; }
public Guid ShipmentId { get; init; }
public DateTime Timestamp { get; init; }
public string Location { get; init; } = string.Empty;
public ShipmentStatus Status { get; init; }
}
Right-click the Interfaces folder and select Add > Interface. Name it ITrackingRepository.cs.
Stop guessing what to test. Start building test suites that actually catch bugs, survive refactoring, and run fast in your CI/CD pipeline.
Testing .NET Applications Fundamentals is a hands-on guide for intermediate C# developers who want to move beyond ad-hoc debugging into systematic, professional testing. You'll build a complete test suite for ParcelPilot, a realistic logistics application with ASP.NET Core APIs, a Blazor admin interface, and Entity Framework Core persistence. Every technique is demonstrated in context, not in throwaway snippets.
What's inside:
Unit testing with xUnit and NUnit, including parameterized tests, shared fixtures, and async patterns
Mocking strategies with Moq and NSubstitute, with clear guidance on when to use fakes instead
Designing code for testability using constructor injection, clock abstractions, and gateway patterns
Test-Driven Development with complete red-green-refactor walkthroughs for domain logic
Integration testing ASP.NET Core APIs using WebApplicationFactory with authentication, dependency overrides, and realistic HTTP assertions
Testing EF Core data access with transaction isolation, concurrency handling, and real SQL Server queries
Blazor component testing with bUnit, covering rendering, event callbacks, and JavaScript interop
End-to-end browser automation with Playwright using Page Object Models and database seeding
Code coverage analysis with Coverlet and ReportGenerator, focused on meaningful metrics rather than percentage chasing
CI/CD pipeline integration with test categorization, flaky test quarantine, and quality gate enforcement
Each of the 13 chapters includes step-by-step code you can type and run, a consolidated Full Example, common mistakes to avoid, a mini quiz with answers, and a hands-on activity. The book targets .NET 10 and covers cross-platform development with Visual Studio and the .NET CLI.
Whether you're adding tests to an existing codebase, establishing team standards, or building testing into your workflow from day one, this book gives you the patterns and practices that scale.
Release DateApril 1, 2026
GenreSoftware & AI Development
ISBN979-8-90377-021-2
Read and listen on the go with the unQbd app.Get the app