Alwyn
Alwyn

Reputation: 8337

MassTransit consumer hard to test

I am having 2 issues testing MassTransit consumers:

  1. Sync issue
  2. MessageData

The first one is like this:

var testConsumer = TestFactory.ForConsumer<ImageUploadConsumer>().New(
                test =>
                {
                    test.UseConsumerFactory(new InstanceConsumerFactory<ImageUploadConsumer>(ImageConsumer));                    
                    test.Publish(message, (scenario, context) =>
                    {

                    });                    
                });

            testConsumer.Execute(); //Is non blocking

The following line (below) fails, because this line:

        moqFileMetaRepo.Verify(_ => _.Add(It.IsAny<IFileMeta>()),Times.Once ); 

is executed 9.9/10 before... this line ever did:

    public async Task Consume(ConsumeContext<ImageUploadWithThumb> context)

My fix has been to do

moqFileMetaRepo
            .Setup(repo => repo.Add(It.IsAny<IFileMeta>()))
            .Callback(() => { AutoEvent.Set(); });

And call the following before the assert:

AutoEvent.WaitOne(TimeSpan.FromSeconds(10));

Which is really a lot of work. And makes TDD or Testing in general a hassle, which I fear is only going to get ignored over time.

MessageData issue is another one. Here's the payload I'm sending through

        message = new ImageUploadWithThumb()
        {
            Id = Guid.NewGuid(),
            FileName = "Test.jpg",
            User = "Me",
            Extension = "jpg",
            OriginalImage = new ConstantMessageData<byte[]>(new Uri("https://g00gle.com"), new byte[] { 1, 2, 3 })
        };

I'm expecting to get byte[] { 1, 2, 3 } on the other end without having to resort to creating an actual persistence.

Instead: Got an error

On the sender side the MessageData.Value resolves ok. The consumer totally bombs. Works in prod though =_= which is not where testing should be.

I really just want to mock and UnitTest my consumer w/o having to wrestle with the framework - preferably in under 5 mins or so. Is there a way out while sticking to MT3?

Upvotes: 1

Views: 1065

Answers (1)

Chris Patterson
Chris Patterson

Reputation: 33278

I would suggest looking at the MassTransit.TestFramework package. It does require NUnit, but you could always take the classes and port it to your own test framework.

All of the MassTransit unit tests are written using the fixtures in this framework. The original .Testing namespace is in a world of hurt right not, it didn't survive completely and I'm unsure it's actually working completely. It wasn't designed for async, so it was difficult to transition without trashing it entirely.

Upvotes: 1

Related Questions