Lesson 69 of 93 · 6 min read · Updated

Testing CQRS Command Handlers and Pipeline Behaviors Without MediatR

Many .NET projects send commands through a mediator: a command goes into a pipeline of behaviors such as validation or logging, and then reaches its handler. MediatR made this pattern popular, but MediatR 13 and later versions require a commercial licence. This lesson uses a small hand-written dispatcher with the same concepts, so you can see the mechanism instead of a library. It then shows a three-part test strategy that works the same way whether you use this dispatcher, MediatR or any similar library.

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
  6. Microsoft.Extensions.DependencyInjection 11.0.0

The Pattern in About 100 Lines

The abstractions are four interfaces. Each one has a direct MediatR equivalent:

This sampleMediatR
ICommand<TResult>IRequest<TResponse>
ICommandHandler<TCommand, TResult>IRequestHandler<,>
ICommandPipelineBehavior<,>IPipelineBehavior<,>
ICommandDispatcher.SendAsyncIMediator.Send
services.AddApplication()services.AddMediatR(...)

M08.LayeredDdd/Application/Cqrs/Abstractions.cs

/// <summary>A command that returns a result (CQRS: Command).</summary>
public interface ICommand<TResult>;

/// <summary>A use case that handles a command.</summary>
public interface ICommandHandler<in TCommand, TResult>
where TCommand : ICommand<TResult>
{
Task<TResult> HandleAsync(TCommand command, CancellationToken cancellationToken = default);
}

/// <summary>
/// Shared behavior wrapped AROUND the handler (validation, logging, transactions...).
/// If <paramref name="next"/> is not called, the chain (and the handler) never runs.
/// </summary>
public interface ICommandPipelineBehavior<in TCommand, TResult>
where TCommand : ICommand<TResult>
{
Task<TResult> HandleAsync(TCommand command, Func<Task<TResult>> next, CancellationToken cancellationToken = default);
}

/// <summary>Delivers a command to the right handler, through the pipeline.</summary>
public interface ICommandDispatcher
{
Task<TResult> SendAsync<TResult>(ICommand<TResult> command, CancellationToken cancellationToken = default);
}

The dispatcher resolves the handler and all behaviors from the container and builds the chain from the inside out. The first registered behavior ends up outermost:

M08.LayeredDdd/Application/Cqrs/CommandDispatcher.cs

var handler = services.GetService(typeof(ICommandHandler<TCommand, TResult>)) as ICommandHandler<TCommand, TResult>
?? throw new InvalidOperationException(
$"'{typeof(TCommand).Name}' için kayıtlı bir handler bulunamadı.");

var behaviors =
services.GetService(typeof(IEnumerable<ICommandPipelineBehavior<TCommand, TResult>>))
as IEnumerable<ICommandPipelineBehavior<TCommand, TResult>>
?? [];

// Build the chain FROM THE INSIDE OUT: first the handler, then wrap the behaviors in reverse order.
Func<Task<TResult>> next = () => handler.HandleAsync(typedCommand, cancellationToken);

foreach (var behavior in behaviors.Reverse())
{
var inner = next;
next = () => behavior.HandleAsync(typedCommand, inner, cancellationToken);
}

return next();

The one behavior in the sample validates the command and short-circuits when there are errors:

M08.LayeredDdd/Application/Cqrs/ValidationBehavior.cs

public sealed class ValidationBehavior<TCommand, TResult>(IEnumerable<ICommandValidator<TCommand>> validators)
: ICommandPipelineBehavior<TCommand, TResult>
where TCommand : ICommand<TResult>
{
public Task<TResult> HandleAsync(
TCommand command, Func<Task<TResult>> next, CancellationToken cancellationToken = default)
{
var errors = validators
.SelectMany(validator => validator.Validate(command))
.ToList();

if (errors.Count > 0)
{
// next() is NOT called, so the handler is never reached (short circuit).
throw new CommandValidationException(errors);
}

return next();
}
}

Three Things to Test, Three Ways to Test Them

A behavior lives outside the handler, and registrations live outside both. Each piece gets the cheapest test that can prove it works:

What is testedHowFile
Handler (the use case)Created with new, no DIPlaceOrderHandlerTests.cs
Behavior (validation)Created with new, with a fake next delegateCommandPipelineTests.cs
Registrations, behavior order, short circuitReal ServiceCollection + AddApplication()CommandPipelineIntegrationTests.cs

Handler tests need nothing new. The handler is created directly with its ports, as in any application layer test, and it does not know a pipeline exists. The other two parts follow.

Unit Testing a Behavior with a Fake next

A behavior is a function that receives next. The test passes a lambda as next and counts how often it runs. No container is needed.

M08.LayeredDdd.Tests/Application/CommandPipelineTests.cs

[Fact]
public async Task ValidationBehavior_WhenCommandIsValid_CallsNextAndReturnsItsResult()
{
// Arrange: "next" is fake; it returns a fixed result instead of a handler.
var sut = new ValidationBehavior<PlaceOrderCommand, PlaceOrderResult>([new PlaceOrderCommandValidator()]);
var expected = PlaceOrderResult.Failure("handler'dan geldi");
var nextCalls = 0;

// Act
var result = await sut.HandleAsync(
Command(new PlaceOrderLine("KLAVYE-01", 1, 750m)),
() => { nextCalls++; return Task.FromResult(expected); });

// Assert: the behavior must pass the result through UNCHANGED.
nextCalls.Should().Be(1);
result.Should().BeSameAs(expected);
}

[Fact]
public async Task ValidationBehavior_WhenCommandIsInvalid_ThrowsAndShortCircuits()
{
var sut = new ValidationBehavior<PlaceOrderCommand, PlaceOrderResult>([new PlaceOrderCommandValidator()]);
var nextCalls = 0;

var act = () => sut.HandleAsync(
Command(new PlaceOrderLine("KLAVYE-01", 0, 750m)),
() => { nextCalls++; return Task.FromResult(PlaceOrderResult.Failure("çalışmamalıydı")); });

var exception = await act.Should().ThrowAsync<CommandValidationException>();
exception.Which.Errors.Should().ContainSingle()
.Which.Should().Be("Satır 1: adet pozitif olmalıdır.");

// SHORT CIRCUIT: the handler was never reached.
nextCalls.Should().Be(0);
}

BeSameAs checks reference equality. It proves the behavior returns the exact object from next and does not wrap or copy it. The nextCalls counter proves the short circuit: when validation fails, the inner chain never runs. The validator itself is tested the same way, as a pure function, in the same file.

Integration Testing the Real Registrations

Unit tests cannot find a missing registration, a behavior registered with the wrong generic shape or a lifetime error. Those only appear when a real container resolves the graph. The integration test calls the production AddApplication() method:

M08.LayeredDdd/Application/ApplicationServiceRegistration.cs

public static IServiceCollection AddApplication(this IServiceCollection services)
{
services.AddScoped<ICommandDispatcher, CommandDispatcher>();

// Handlers
services.AddScoped<ICommandHandler<PlaceOrderCommand, PlaceOrderResult>, PlaceOrderHandler>();

// Validators
services.AddSingleton<ICommandValidator<PlaceOrderCommand>, PlaceOrderCommandValidator>();

// Pipeline behaviors: OPEN GENERIC registration, applies to every command.
// Registration order = execution order (the first registered is outermost).
services.AddScoped(typeof(ICommandPipelineBehavior<,>), typeof(ValidationBehavior<,>));

return services;
}

M08.LayeredDdd.Tests/Application/CommandPipelineIntegrationTests.cs

var services = new ServiceCollection();

// Production registrations: THIS is what is being tested.
services.AddApplication();

// Ports: the outermost infrastructure is in memory (the host's/Infrastructure's job).
services.AddSingleton<IOrderRepository>(orders);
services.AddSingleton<IDomainEventPublisher, InMemoryDomainEventPublisher>();
services.AddSingleton(customers.Object);
services.AddSingleton<TimeProvider>(new FakeTimeProvider(Now));

configure?.Invoke(services);

// ValidateOnBuild + ValidateScopes: missing dependencies and scope errors fail at BUILD time.
var provider = services.BuildServiceProvider(new ServiceProviderOptions
{
ValidateOnBuild = true,
ValidateScopes = true,
});

With the real provider, one test sends an invalid command through the dispatcher and proves the handler never ran: the customer port was not queried and nothing was saved.

M08.LayeredDdd.Tests/Application/CommandPipelineIntegrationTests.cs

[Fact]
public async Task SendAsync_WithInvalidCommand_IsRejectedBeforeReachingHandler()
{
var harness = CreateHarness();
using var scope = harness.Provider.CreateScope();
var dispatcher = scope.ServiceProvider.GetRequiredService<ICommandDispatcher>();
var command = Command(new PlaceOrderLine("", 1, 750m));

var act = () => dispatcher.SendAsync(command);

await act.Should().ThrowAsync<CommandValidationException>();

// PROOF that the handler was not reached: no port was queried and nothing was saved.
harness.Customers.Verify(
x => x.IsLoyalAsync(It.IsAny<CustomerId>(), It.IsAny<CancellationToken>()),
Times.Never);
(await harness.Orders.GetAsync(command.OrderId)).Should().BeNull();
}

Another test registers two recording behaviors and checks the exact sequence:

M08.LayeredDdd.Tests/Application/CommandPipelineIntegrationTests.cs

// Assert: onion layers, the first registered is outermost.
// Checking the ORDER is LEGITIMATE here: the order is the behavior under test.
log.Should().Equal("dış:önce", "iç:önce", "iç:sonra", "dış:sonra");

The log entries mean "outer:before", "inner:before", "inner:after", "outer:after". Order checks are usually fragile, but here the order is the contract: validation must run before a transaction behavior, for example. A last test sends a command that has no handler and checks that the error message names the command, so a missing registration is easy to diagnose.

A common mistake is to unit test the dispatcher with a mocked IServiceProvider. Such a test only proves that the mock was set up the way the dispatcher expects. The dispatcher's correctness is about real resolution, so it is proven by the integration test above.

Summary

  1. MediatR 13+ is commercial; the same command, handler and behavior pattern fits in a small hand-written dispatcher.
  2. Test the handler directly with new; it does not need the pipeline.
  3. Test a behavior with a fake next delegate and count its calls to prove pass-through and short circuit.
  4. Test registrations, behavior order and short circuit with a real ServiceCollection and the production AddApplication().
  5. Use ValidateOnBuild and ValidateScopes so missing dependencies and lifetime errors fail at build time.
  6. The same strategy applies unchanged to MediatR or any similar library.