Home > front end >  Azure service bus consumer tests
Azure service bus consumer tests

Time:01-11

I'm currently working on a net core 7 c#, service that consume a azure service bus queue using masstransit.

The thing is the consumer is working as expected, but now I've to create a Nunit test and Idk hot to write a test like that.

My consumer is waiting for an azure service bus. So when the queue receives one message, this consumer get fired and receive the "dataset downloaded" message in it's "consume method".

Idk how to test this using mocks. It's my first time making a test for a method that is called by an app that is outside of my solution... So how should I raise the event... ?

We are using Nunit. Nsubstitute for mocks and nfluent

code

Create a test with Nunit nsubstitute and nfluent for a worker consumer that is waiting to be called by a azure service bus with masstransit, when the queue receives a message.

CodePudding user response:

You can test your consumer using the test harness, which provides an in-memory transport for testing your consumer. This is explained in the documentation.

CodePudding user response:

One approach you could take to testing your MassTransit consumer is to use a test harness provided by MassTransit, such as InMemoryTestHarness. This harness allows you to send messages to your consumer and make assertions about how it handles those messages, without the need to actually set up and connect to an Azure Service Bus.

Here is an example of how you could set up and use the InMemoryTestHarness to test your consumer:

[TestFixture]
public class MyConsumerTests
{
private InMemoryTestHarness _testHarness;
private MyConsumer _consumer;

[SetUp]
public void SetUp()
{
    // Set up the test harness
    _testHarness = new InMemoryTestHarness();

    // Set up your consumer
    _consumer = new MyConsumer();

    // Add the consumer to the test harness
    _testHarness.Consumer(_consumer);
}

[Test]
public async Task Test_MyConsumer_Handles_DatasetDownloaded_Message()
{
    // Arrange
    var datasetDownloadedMessage = new DatasetDownloadedMessage();

    // Act
    await _testHarness.Send(datasetDownloadedMessage);

    // Assert
    // Make assertions about how your consumer handled the message
    // For example:
    _consumer.Received().Consume(Arg.Is<DatasetDownloadedMessage>(m => m == datasetDownloadedMessage));
}
}

I have a video and some sample code showing how to manage and test using MassTransit.

https://www.youtube.com/watch?v=ubBW2bG0VbY&ab_channel=GarryTaylor

The talk about testing is towards the end of the video, but it's worth a read :)

  • Related