Lesson 35 of 93 · 7 min read · Updated

Abstractions and Dependency Injection as Test Seams in C#

A seam is a place where you can change what a piece of code talks to without editing that code. In .NET the most common seam is a constructor that takes an interface. This lesson walks through a CheckoutService whose constructor openly declares four dependencies, and shows why each one is a seam that a unit test can use. The same service is the system under test for the rest of the Moq lessons.

Technical Requirements

  1. .NET 11 SDK
  2. Microsoft.Extensions.Logging abstractions (part of the shared framework in .NET 11, no extra package needed for ILogger<T>)
  3. For the test side: xUnit 2.9.3, Moq 4.21.0, Microsoft.Extensions.TimeProvider.Testing 11.0.0

The Domain Types

Before looking at the service, here are the two small value types it works with. Money is a value object with an amount and a currency. Coupon knows whether it is valid at a given moment.

M05.TestableDesign/Domain/Money.cs

namespace M05.TestableDesign.Domain;

/// <summary>Money: amount + currency. A value object.</summary>
public readonly record struct Money(decimal Amount, string Currency)
{
public static Money Try(decimal amount) => new(amount, "TRY");

public Money Subtract(Money other)
{
if (Currency != other.Currency)
{
throw new InvalidOperationException(
$"Farklı para birimleri çıkarılamaz: {Currency} / {other.Currency}");
}

return this with { Amount = Amount - other.Amount };
}

public override string ToString() => $"{Amount:0.00} {Currency}";
}

M05.TestableDesign/Domain/Coupon.cs

namespace M05.TestableDesign.Domain;

/// <summary>Discount coupon.</summary>
public sealed record Coupon(string Code, decimal DiscountRate, DateTimeOffset ExpiresAt)
{
/// <summary>
/// Is the coupon valid at the given INSTANT?
/// Note: we do not read "now" from the inside, we receive it from OUTSIDE.
/// This small choice is exactly what makes the class testable.
/// </summary>
public bool IsValidAt(DateTimeOffset instant) => instant < ExpiresAt;
}

Coupon.IsValidAt takes the instant as a parameter. It never calls DateTime.UtcNow. That one decision means a test can check an expired coupon and a valid coupon with plain values, and no fake is needed.

Narrow Interfaces at Real Boundaries

The service talks to two things outside the process: a payment provider and a coupon store. Each one is behind a narrow interface.

M05.TestableDesign/Ports/Ports.cs

using M05.TestableDesign.Domain;

namespace M05.TestableDesign.Ports;

/// <summary>Payment gateway response.</summary>
public sealed record Authorization(bool Approved, string? Reference, string? DeclineReason)
{
public static Authorization Approve(string reference) => new(true, reference, null);
public static Authorization Decline(string reason) => new(false, null, reason);
}

/// <summary>
/// Payment gateway: an OUT-OF-PROCESS boundary. Slow, costs money, not always up.
/// It is always faked in a unit test.
/// </summary>
public interface IPaymentGateway
{
Task<Authorization> AuthorizeAsync(Money amount, CancellationToken cancellationToken = default);

Task CaptureAsync(string reference, Money amount, CancellationToken cancellationToken = default);
}

/// <summary>Coupon repository (database boundary).</summary>
public interface ICouponRepository
{
Task<Coupon?> FindAsync(string code, CancellationToken cancellationToken = default);
}

These interfaces exist for a reason that has nothing to do with tests. A real payment gateway can be replaced by another provider. A coupon store can move from one database to another. The interfaces describe what the application needs from those systems, with only the methods it uses. That is why they make good seams: they sit where the system really touches something it does not control.

Avoid the opposite habit of adding an interface to every class "so that we can mock it". An interface in front of pure in-process logic, such as Coupon.IsValidAt, adds a layer and gives nothing back. Test that logic directly.

The Constructor Declares the Test Cost

Here is the service. Read the constructor first.

M05.TestableDesign/CheckoutService.cs

/// <summary>
/// This class's constructor openly DECLARES the cost of testing it:
/// if you see 4 dependencies, a test has 4 things to control.
///
/// Things to notice:
/// Time comes from OUTSIDE (TimeProvider) -> NO DateTime.UtcNow.
/// Boundaries are NARROW interfaces; they exist not "so we can mock them",
/// but because they really can be swapped for different technologies.
/// The CancellationToken is passed down.
/// </summary>
public sealed class CheckoutService(
IPaymentGateway paymentGateway,
ICouponRepository couponRepository,
TimeProvider timeProvider,
ILogger<CheckoutService> logger)
{
/// <summary>Log event used when a coupon is not found or has expired.</summary>
public static readonly EventId CouponRejected = new(1001, nameof(CouponRejected));

public async Task<CheckoutResult> PayAsync(
Money total,
string? couponCode,
CancellationToken cancellationToken = default)
{
if (total.Amount <= 0)
{
return CheckoutResult.Failed("Tutar pozitif olmalıdır.");
}

var payable = total;

if (!string.IsNullOrWhiteSpace(couponCode))
{
var coupon = await couponRepository.FindAsync(couponCode, cancellationToken);

// "Now" comes from OUTSIDE: in a test we can jump to any time we want.
var now = timeProvider.GetUtcNow();

if (coupon is null || !coupon.IsValidAt(now))
{
// Structured log: the contract is the event id and the properties,
// not the message text.
logger.LogWarning(
CouponRejected,
"Kupon reddedildi. Kod: {CouponCode}",
couponCode);
}
else
{
var discount = Money.Try(
decimal.Round(total.Amount * coupon.DiscountRate, 2, MidpointRounding.AwayFromZero));
payable = total.Subtract(discount);
}
}

var authorization = await paymentGateway.AuthorizeAsync(payable, cancellationToken);

if (!authorization.Approved)
{
return CheckoutResult.Failed(authorization.DeclineReason ?? "Ödeme reddedildi.");
}

await paymentGateway.CaptureAsync(authorization.Reference!, payable, cancellationToken);

return CheckoutResult.Success(authorization.Reference!, payable);
}
}

The primary constructor lists four dependencies. Each one maps to a seam:

DependencyProductionUnit test
IPaymentGatewayHTTP client for the payment providerMoq or NSubstitute double
ICouponRepositoryDatabase repositoryMoq double returning a test coupon
TimeProviderTimeProvider.SystemFakeTimeProvider at a fixed instant
ILogger<CheckoutService>Logger from the hostNullLogger or a recording logger

Four parameters tell you a test has four things to arrange. That is useful information. If the list grows to eight or ten, the constructor is warning you that the class does too much, long before the test becomes painful.

Two more details matter. First, the CancellationToken flows down to every boundary call, so cancellation can be tested too. Second, the log call uses an EventId and a named placeholder {CouponCode}. A later lesson verifies the log through those two items instead of the formatted sentence.

Using the Seams in a Test

A test builds the service by passing a double for each seam. The helper below is the shared setup used by the Moq tests.

M05.TestableDesign.Tests/MoqBasicsTests.cs

private static readonly DateTimeOffset Now = new(2026, 3, 14, 10, 0, 0, TimeSpan.Zero);

/// <summary>Collects the shared test setup in one place.</summary>
private static (CheckoutService Sut, Mock<IPaymentGateway> Gateway, Mock<ICouponRepository> Coupons)
CreateSut(FakeTimeProvider? clock = null)
{
var gateway = new Mock<IPaymentGateway>();
var coupons = new Mock<ICouponRepository>();

var sut = new CheckoutService(
gateway.Object,
coupons.Object,
clock ?? new FakeTimeProvider(Now),
NullLogger<CheckoutService>.Instance);

return (sut, gateway, coupons);
}

The production code does not change at all. It does not know it is running in a test. The test simply passes different objects through the same constructor that the dependency injection container uses in production.

In the application host, the same four dependencies come from the container. You register the real gateway and repository, register TimeProvider.System as the singleton TimeProvider, and the logging infrastructure supplies ILogger<CheckoutService>. The test and the host use the same seam with different objects behind it.

Summary

  1. A seam is a place where a test can swap a collaborator without editing the code; a constructor that takes an abstraction is the usual seam in .NET.
  2. Put interfaces at real boundaries such as payment providers and databases, not in front of every class.
  3. Pass time in through TimeProvider or as a method parameter, as Coupon.IsValidAt does.
  4. The constructor parameter list is the test cost: each dependency is one thing a test must arrange.
  5. Flow the CancellationToken down and log with an EventId and named properties so both are testable later.