Lesson 70 of 93 · 5 min read · Updated

Subcutaneous Tests: Testing a Full Use Case Just Below the UI

End-to-end tests that drive a browser or an HTTP API are slow, need a running host and break for reasons unrelated to business logic. Isolated unit tests are fast but each one sees only a small piece. A subcutaneous test sits between them: it enters the application just below the presentation layer, runs the real application and domain layers from start to finish, and replaces only the outermost infrastructure. This lesson builds such a test for an order that is placed and then cancelled, and explains where this kind of test should stop.

Technical Requirements

  1. .NET 11 SDK
  2. xUnit 2.9.3
  3. FluentAssertions 7.2.2
  4. Moq 4.21.0
  5. Microsoft.Extensions.TimeProvider.Testing 11.0.0

What "Subcutaneous" Means

The name means "under the skin". The skin is the user interface or the HTTP layer: controllers, minimal API endpoints, model binding, serialization, authentication middleware. A subcutaneous test does not go through any of that. It calls the application layer directly, the way a controller would after it has parsed the request.

Below that entry point, everything is real: the use case handler, the aggregate, its invariants and its events. Only the parts that leave the process, such as the database or the message broker, are replaced with light in-memory implementations.

Test typeEntry pointReal codeReplaced
Isolated unit testOne class or methodThat class onlyIts collaborators
Subcutaneous testApplication layer, below the UIApplication + DomainOutermost infrastructure (DB, queue)
End-to-end testBrowser or HTTP requestEverythingUsually nothing

The subcutaneous test is wider than a unit test, and faster and more focused than a full end-to-end test.

The Test: Place, Then Cancel

The scenario covers a complete order lifecycle. A loyal customer places an order with two lines. Two hours later the order is cancelled. The test checks the final saved state and both published events, including their timestamps.

M08.LayeredDdd.Tests/Application/SubcutaneousTests.cs

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

[Fact]
public async Task PlaceThenCancel_FullUseCaseFlowThroughRealLayers()
{
// Arrange: ONLY the outermost infrastructure is in memory; Domain and Application are REAL.
var orders = new InMemoryOrderRepository();
var events = new InMemoryDomainEventPublisher();
var customers = new Mock<ICustomerDirectory>();
customers
.Setup(x => x.IsLoyalAsync(It.IsAny<CustomerId>(), It.IsAny<CancellationToken>()))
.ReturnsAsync(true);

var clock = new FakeTimeProvider(Now);
var handler = new PlaceOrderHandler(orders, customers.Object, events, clock);

var command = new PlaceOrderCommand(
OrderId.New(),
CustomerId.New(),
[new PlaceOrderLine("KLAVYE-01", 2, 750m), new PlaceOrderLine("MOUSE-01", 1, 250m)]);

// Act 1: place the order
var placeResult = await handler.HandleAsync(command);

// Act 2: cancel through the saved aggregate
var saved = await orders.GetAsync(command.OrderId);
clock.Advance(TimeSpan.FromHours(2));
saved!.Cancel("Müşteri vazgeçti", clock.GetUtcNow());
await orders.SaveAsync(saved);
await events.PublishAsync(saved.DequeueEvents());

// Assert: the observable end-to-end outcome
placeResult.IsSuccessful.Should().BeTrue();
placeResult.Total.Should().Be(1_750m);

var reloaded = await orders.GetAsync(command.OrderId);
reloaded!.Status.Should().Be(OrderStatus.Cancelled);

events.Published.Should().HaveCount(2);
events.Published.OfType<OrderPlaced>().Should().ContainSingle()
.Which.OccurredAt.Should().Be(Now);
events.Published.OfType<OrderCancelled>().Should().ContainSingle()
.Which.OccurredAt.Should().Be(Now.AddHours(2));
}
}

Reading the Test Step by Step

Arrange. The repository and the event publisher are the in-memory adapters from the Infrastructure layer. They behave like real storage for the duration of the test: what is saved can be loaded again. The customer directory stands for an external service, so it is a mock that always answers "loyal". The clock is a FakeTimeProvider that starts at a fixed instant.

Act 1. The real PlaceOrderHandler runs. It asks the customer directory, builds a real Order, adds the lines, applies the aggregate rules, places the order with the fake clock's time, saves it and publishes the OrderPlaced event.

Act 2. The sample has no cancel handler, so the test plays that part itself. It loads the saved aggregate, moves the clock forward two hours with clock.Advance, calls the real Cancel method, saves the aggregate and publishes the events it collected. These are the same steps a cancel use case would perform, in the same order the place handler uses: save first, then publish.

Assert. The test checks only outcomes that an outside observer could see. The result reports success with the correct total (2 x 750 + 250 = 1,750). The reloaded order is cancelled. Exactly two events were published, one of each type, and each carries the time at which it happened.

Why the Fake Clock Matters Here

The assertion OccurredAt.Should().Be(Now.AddHours(2)) is only possible because time is controlled. With the system clock, the test could at best check that the cancel event came "after" the place event, which proves much less. FakeTimeProvider.Advance lets a test move through hours or days of business time in a single line, without waiting. The handler receives the same clock object, so the place event and the cancel event read their time from one source.

Where a Subcutaneous Test Stops

A subcutaneous test stops at the presentation layer. It does not check routing, status codes, JSON shape, authentication or model validation attributes. Those belong to a small number of HTTP-level tests, for example with WebApplicationFactory. It also does not check the real database mapping; that belongs to integration tests against a real database engine.

Use subcutaneous tests for high-value use cases whose application API is stable: placing an order, completing a payment, closing an account. They give strong confidence that the parts work together, at a cost close to a unit test.

A common mistake is to write many subcutaneous tests for every edge case. Each one sets up more objects and fails for more reasons than a unit test. Keep edge cases in the domain and handler tests, and use a few subcutaneous tests for the main flows. Another mistake is to let the test reach into internals between steps, for example by changing the aggregate's state directly. The test should move only through the same public operations a real caller would use.

Summary

  1. A subcutaneous test enters below the UI and runs the real application and domain layers.
  2. Only the outermost infrastructure, such as storage and messaging, is replaced with in-memory implementations.
  3. Assert only observable outcomes: results, saved state and published events.
  4. A FakeTimeProvider with Advance makes timestamps across several steps deterministic.
  5. Keep subcutaneous tests few and focused on high-value flows; leave edge cases to unit tests and HTTP details to HTTP tests.