Home > Net >  Testing MassTransit consumer with mediator
Testing MassTransit consumer with mediator

Time:08-25

I have consumer CarCreatedConsumer which I want to unit test

public class CarCreatedConsumer: IConsumer<CarCreatedEvent>
{
   private readonly IMediator _mediator;
   public CarCreatedConsumer(IMediator mediator)
   {
        _mediator = mediator;
   }
   public async Task Consume(ConsumeContext<CarCreatedEvent> context)
   {
      ....
   }
}

Using MassTransit.Testing I'm trying to write test for event consumer

[TestFixture]
public class MyTests
{
   private ServiceProvider _provider;
   private InMemoryTestHarness _harness;

   [SetUp]
   public void SetUp()
   {
     _provider = new ServiceCollection()
       .AddMassTransitInMemoryTestHarness(cfg =>
       {
          cfg.AddConsumer<CarCreatedConsumer>();
       }).AddMediator()
      .BuildServiceProvider(true);
         
      _harness = _provider.GetRequiredService<InMemoryTestHarness>();
   }
   
  [Test]
  public async Task MessageShouldBeConsumed()
  {
     await _harness.Start();
    try
    {
     await _harness.InputQueueSendEndpoint.Send<CarCreatedEvent>(new 
     {
        CarId = Guid.NewGuid.ToString(),
        CarOwnerName = "John Stuart"
        ...
     }
        // Always false
        Assert.True(_harness.Consumed.Select<CarCreatedEvent>().Any());
    }
    finally
    {
       await _harness.Stop();
    }
  }
}

I'm expect this to return true but it fails (returns false). Obviously I'm doing something wrong, any ideas?

CodePudding user response:

Your test harness usage is suspect, and is also using an obsolete version of the configuration. I'd suggest reading the documentation on the current test harness and how to test your consumer.

  • Related