Lesson 28 of 93 · 6 min read · Updated

Test Doubles in .NET: Controlling a Class's Collaborators in Unit Tests

A unit test should check one piece of logic, but most real classes do not work alone. They call a database, a counter, an email server or a log. A test double is an object that stands in for one of those collaborators so the test controls what the class sees and can observe what it does. This lesson introduces the order service used across this series and shows the four collaborator boundaries it has, and why each one calls for a different kind of double.

Technical Requirements

  1. .NET 11 SDK
  2. xUnit 2.9.3
  3. No mocking library. Every double in this series is written by hand, so you see exactly what a library such as Moq generates for you later.

The System Under Test: OrderService

The class we test places an order. It checks stock, reserves it, gets an order number, sends a confirmation email and writes an audit entry. It takes all four collaborators through its primary constructor, which means a test can pass in any implementation it wants.

M04.TestDoubles/OrderService.cs

using M04.TestDoubles.Ports;

namespace M04.TestDoubles;

/// <summary>
/// The "place order" use case.
///
/// It has four different collaborators. The goal is to learn to pick
/// the LIGHTEST test double for each of them:
///
/// IAuditLog → not used in most tests → Dummy
/// IInventory → supplies input to the scenario → Stub / Fake
/// IOrderNumberGenerator → controlled, deterministic output → Stub
/// IEmailSender → unobservable external effect → Mock / Spy
/// </summary>
public sealed class OrderService(
IInventory inventory,
IOrderNumberGenerator orderNumberGenerator,
IEmailSender emailSender,
IAuditLog auditLog)
{
public OrderResult Place(string customerEmail, IReadOnlyList<OrderLine> lines)
{
ArgumentException.ThrowIfNullOrWhiteSpace(customerEmail);
ArgumentNullException.ThrowIfNull(lines);

if (lines.Count == 0)
{
return OrderResult.Failure("Sipariş en az bir satır içermelidir."); // "An order must contain at least one line."
}

// 1) Stock check: we take INPUT from IInventory (a query).
foreach (var line in lines)
{
if (inventory.AvailableQuantity(line.Sku) < line.Quantity)
{
auditLog.Write($"Stok yetersiz: {line.Sku}"); // "Insufficient stock"
return OrderResult.Failure($"'{line.Sku}' için yeterli stok yok."); // "Not enough stock for ..."
}
}

// 2) Reservation: we change STATE on IInventory (a command).
foreach (var line in lines)
{
inventory.Reserve(line.Sku, line.Quantity);
}

var orderNumber = orderNumberGenerator.Next();

// 3) Notification: an unobservable external effect. Only a MOCK can verify it.
emailSender.SendOrderConfirmation(customerEmail, orderNumber);

auditLog.Write($"Sipariş oluşturuldu: {orderNumber}"); // "Order created"

return OrderResult.Success(orderNumber);
}

/// <summary>Order total: a pure calculation that uses no collaborator.</summary>
public static decimal Total(IReadOnlyList<OrderLine> lines) =>
lines.Sum(l => l.Quantity * l.UnitPrice);
}

The four interfaces are the seams of this class. A seam is a place where you can swap one implementation for another without editing the code under test. In production, a dependency injection container passes the real database-backed inventory and the real SMTP sender. In a test, you pass small classes that you write yourself. The service cannot tell the difference, and that is the whole point: the logic inside Place runs exactly as it would in production, but every call that leaves the class lands on an object the test owns.

The method returns an OrderResult instead of throwing for business failures. That matters for testing: a returned value is the easiest thing to assert on.

M04.TestDoubles/Order.cs

namespace M04.TestDoubles;

/// <summary>An order line.</summary>
public sealed record OrderLine(string Sku, int Quantity, decimal UnitPrice);

/// <summary>Result object that describes the outcome (the "result" pattern instead of exceptions).</summary>
public sealed record OrderResult(bool IsSuccessful, string? OrderNumber, string? FailureReason)
{
public static OrderResult Success(string orderNumber) => new(true, orderNumber, null);
public static OrderResult Failure(string reason) => new(false, null, reason);
}

Four Boundaries, Four Different Roles

Each collaborator sits behind a small interface. Look at what each one does for the service, not at what it is called. The role decides which double fits.

M04.TestDoubles/Ports/IInventory.cs

namespace M04.TestDoubles.Ports;

/// <summary>Stock store boundary. In production this would be a database or a service.</summary>
public interface IInventory
{
/// <summary>Available stock for the given SKU.</summary>
int AvailableQuantity(string sku);

/// <summary>Reserves stock.</summary>
void Reserve(string sku, int quantity);
}

IInventory has a query (AvailableQuantity) and a command (Reserve). The query feeds input into the scenario: "is there stock?" The command changes state. If your test only needs the answer to the query, a double that returns a fixed value is enough. If the test needs the stock to really go down, the double must keep state.

M04.TestDoubles/Ports/IOrderNumberGenerator.cs

namespace M04.TestDoubles.Ports;

/// <summary>Order number generator (in production a counter or a database sequence).</summary>
public interface IOrderNumberGenerator
{
string Next();
}

A real generator would hand out a new number each time. Tests need a known value so they can assert on it. A double that always returns the same string makes the test deterministic.

M04.TestDoubles/Ports/IEmailSender.cs

namespace M04.TestDoubles.Ports;

/// <summary>
/// Email sending: an OUT-OF-PROCESS, UNOBSERVABLE side effect.
/// It cannot be verified through a return value or a state change, so
/// a MOCK (behaviour verification) is legitimate for this boundary.
/// </summary>
public interface IEmailSender
{
void SendOrderConfirmation(string toAddress, string orderNumber);
}

SendOrderConfirmation returns nothing and changes nothing the test can read. The only way to know an email was sent is to record or check the call itself. This is the one boundary where verifying an interaction is the right tool.

M04.TestDoubles/Ports/IAuditLog.cs

namespace M04.TestDoubles.Ports;

/// <summary>
/// Audit log. In this scenario it does not matter for the BUSINESS OUTCOME.
/// Some tests pass it only to "fill the parameter" → DUMMY.
/// </summary>
public interface IAuditLog
{
void Write(string message);
}

The audit log does not affect whether the order succeeds. Most tests only pass something because the constructor demands it.

Mapping Roles to Doubles

Putting it together gives a simple map. This series covers each row in its own lesson.

CollaboratorRole in the testTypical double
IAuditLogRequired by the constructor, not part of the scenarioDummy
IInventorySupplies input, sometimes needs real stateStub or Fake
IOrderNumberGeneratorMust return a known, repeatable valueStub
IEmailSenderOutgoing effect with no return valueSpy or Mock

Notice the method Total. It is static and uses no collaborator at all, so its test needs no double. When a piece of logic can be pulled out into a pure function like this, the test gets simpler. Keep that in mind: the best double is often no double.

A common mistake is to pick one double type and use it everywhere, for example mocking every interface and verifying every call. That ties the test to the internal steps of the method. If you later reorder the stock check or cache a query, the test breaks even though the behaviour the customer sees is the same. Choosing per boundary avoids that.

Summary

  1. A test double replaces a collaborator so the test controls the inputs and can observe the outputs of the class under test.
  2. OrderService has four collaborators, and each one plays a different role: unused, input provider, deterministic value, outgoing effect.
  3. The role of the collaborator, not its name, decides which double to use.
  4. Queries feed input; commands change state; outgoing calls with no return value are the only place where interaction checks make sense.
  5. Pure logic such as Total needs no double at all. The next lesson starts with the two simplest doubles: Dummy and Stub.