Skip to content

Testing

ferdi kurnaz edited this page Sep 1, 2026 · 1 revision

Testing

Mediatron's own test suite uses xUnit, FluentAssertions, and NSubstitute. You can use the same tools to test the handlers you write in your own project.

Running Mediatron's Tests

If you cloned the repository, you can run the test suite with:

dotnet test

Testing Your Own Handlers

Because a handler is just a plain class, you can unit test it directly, without needing the mediator at all:

[Fact]
public async Task Handle_Should_Return_Generated_Product_Id()
{
    // Arrange
    var handler = new CreateProductCommandHandler();
    var command = new CreateProductCommand("Laptop", 999.99m);

    // Act
    var result = await handler.Handle(command, CancellationToken.None);

    // Assert
    result.Should().Be(42);
}

Testing with a Fake IMediator

For controller or service tests, you can substitute IMediator with NSubstitute so you don't run real handler logic:

[Fact]
public async Task Create_Should_Return_Ok_With_Product_Id()
{
    // Arrange
    var mediator = Substitute.For<IMediator>();
    mediator.SendAsync<CreateProductCommand, int>(Arg.Any<CreateProductCommand>())
            .Returns(42);

    var controller = new ProductsController(mediator);

    // Act
    var result = await controller.Create(new CreateProductCommand("Laptop", 999.99m));

    // Assert
    result.Should().BeOfType<OkObjectResult>();
}

Next: FAQ

Clone this wiki locally