Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Testing MassTransit consumer with mediator

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading