Search code examples
c#azure-functionsazureservicebusxunitdotnet-isolated

How to use xUnit to test code when Azure Service bus throws Transient exceptions


I have an Azure Service Bus Trigger function that has the job of replicating the incoming message from a topic and sending it to another service bus topic.

I send the incoming message to the service bus in the other region using Azure.Messaging.ServiceBus.ServiceBusSender.SendMessageAsync()

I need to write a xUnit test to ensure the right behaviour is being followed when the topic/service bus in the other region is unavailable. Is there a way to simulate the SendMessageAsync() method throwing one of the transient exceptions to test this?


Solution

  • You can mock ServiceBusSender.

    e.g. using NSubstitute + xUnit

    [Fact]
    public void Test1()
    {
        // Arrange
        var mockSender = Substitute.For<ServiceBusSender>();
        mockSender.SendMessageAsync(default).ThrowsForAnyArgs(new Exception("Example exception"));
    
        // Act
        var testClass = new YourClass(mock);
        testClass.DoSomething();
    
        // Assert
    }