Test using OpenTelemetry
MassTransit has a telemetry listener that may be used to track and display OpenTelemetry traces generated by a unit test. When the test completes, the traces are displayed in the console.
Configure the telemetry listener
Section titled “Configure the telemetry listener”To configure the telemetry listener, add the following code to the ConfigureServices method of the test fixture:
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() .AddTelemetryListener() .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>());
Assert.That(await harness.Published.Any<OrderCreated>()); }}View the Telemetry
Section titled “View the Telemetry”Once the test completes, the traces are displayed in the console. If you are using NUnit, the traces are displayed in the test results.
┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┯━━━━━━━━━━┯━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓┃ CreateOrderConsumerTests │ Duration │ Timeline ┃┠─────────────────────────────────────────────────────────────────────────────┼──────────┼────────────────────────────────────────────────────┨┃ Should_create_an_order_and_produce_an_event │ 420ms │ ▐▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▍ ┃┃ urn:message:MassTransit.Tests.SagaStateMachineTests:CreateOrder send │ 63ms │ ▐▒▒▒▒▒▍ ┃┃ └ CreateOrder receive │ 58ms │ ▐▒▒▒▒▍ ┃┃ └ CreateOrder process │ 24ms │ ▐▍ ┃┃ └ urn:message:MassTransit.Tests.SagaStateMachineTests:OrderCreated send │ 2ms │ ▍ ┃┗━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┷━━━━━━━━━━┷━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛If you are using xUnit, additional configuration is necessary to display the traces.