Test a consumer
In this example, a class is using the request client to check the status of an order.
Create the message contracts
Section titled “Create the message contracts”using System;
public record CreateOrder(Guid OrderId);
public record OrderCreated(Guid OrderId);Create the consumer
Section titled “Create the consumer”A consumer in the application that handles the CreateOrder message.
using System;using System.Threading;using System.Threading.Tasks;using MassTransit;
public class CreateOrderConsumer : IConsumer<CreateOrder>{ public async Task Consume(ConsumeContext<CreateOrder> context) { await context.Publish(new OrderCreated(context.Message.OrderId)); }}Create the test
Section titled “Create the test”To test a Request using the MassTransit Test Harness:
namespace MyProject.Tests;
using System.Threading.Tasks;using NUnit.Framework;using MassTransit;using MassTransit.Testing;
public class CreateOrderConsumerTests{ [Test] public async Task Should_create_an_order_and_produce_an_event() { await using var provider = new ServiceCollection() .AddMassTransitTestHarness(cfg => { cfg.AddConsumer<CreateOrderConsumer>(); }) .BuildServiceProvider(true);
var harness = await provider.StartTestHarness();
var orderId = NewId.NextGuid();
await harness.Bus.Publish(new CreateOrder(orderId));
Assert.That(await harness.Consumed.Any<CreateOrder>(x => x.Message.OrderId == orderId));
Assert.That(await harness.Published.Any<OrderCreated>(x => x.Message.OrderId == orderId)); }}