Test request/response
In a test scenario where a class is using the request client (IRequestClient), a request handler can be configured using the test harness to simulate a response.
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 CheckOrderStatus(Guid OrderId);
public record OrderStatus(Guid OrderId, string Status);Create the component
Section titled “Create the component”A component in the application that uses the request client:
using System;using System.Threading;using System.Threading.Tasks;using MassTransit;
public interface IOrderStatusChecker{ Task<string> GetStatus(Guid orderId, CancellationToken cancellationToken = default);}
public class OrderStatusChecker : IOrderStatusChecker{ private readonly IRequestClient<CheckOrderStatus> _client;
public OrderStatusChecker(IRequestClient<CheckOrderStatus> client) { _client = client; }
public async Task<string> GetStatus(Guid orderId, CancellationToken cancellationToken = default) { // Send a request and await the response var response = await _client.GetResponse<OrderStatus>( new CheckOrderStatus(orderId), cancellationToken );
return response.Message.Status; }}Create the test
Section titled “Create the test”To test a Request using the MassTransit Test Harness:
[Test]public async Task Test_the_order_status_checker(){ await using var provider = new ServiceCollection() .AddMassTransitTestHarness(cfg => { cfg.Handler<CheckOrderStatus>(async context => { await context.RespondAsync(new OrderStatus(context.Message.OrderId, "OK")); }); }) .AddScoped<IOrderStatusChecker, OrderStatusChecker>(); .BuildServiceProvider(true);
var harness = await provider.StartTestHarness();
var component = harness.Scope.ServiceProvider.GetRequiredService<IOrderStatusChecker>()
var status = await component.GetStatus(NewId.NextGuid());
Assert.That(status, Is.EqualTo("OK"));}