18

we want to write unit-test for servicebus message trigger. we are using Azure.Messaging.ServiceBus nuget package

     [FunctionName("serviebustrigger")]
  public async Task Run ([ServiceBusTrigger("xxxxtopic", "xxxxsubscription", Connection = "Abs-Connection", AutoCompleteMessages = false)] ServiceBusReceivedMessage message, ServiceBusMessageActions messageActions)

    {
        _logger.LogInformation($"{nameof(Run)} execution started for MessageId:{{MessageId}}", message.MessageId);
        try
        {
                //some code
             await messageActions.CompleteMessageAsync(message);
        }
        catch (Exception ex)
         {
             await messageActions.DeadLetterMessageAsync(message);
         }
    }

Now I want to write unit test for the above code. But I'm not able mock ServiceBusReceivedMessage and ServiceBusMessageActions as these have Internal Constructor. Can someone suggest me better way to write unit test

  • "//some code" presumably represents the business logic the function implements. The ASB framework already works and has been tested by Microsoft so just test the business code, designing it to be testable without a framework such as ASB. i.e. ServiceBusReceivedMessage contains the data the business logic needs. Mock that data instead. – codebrane Feb 28 '22 at 10:39

1 Answers1

30

There was an oversight with the implementation of ServiceBusMessageActions where the mocking constructor was initially missed. This was corrected in v5.2.0 of the extensions package.

With that fix, a parameterless constructor is available to ensure that ServiceBusMessageActions is usable with a mocking framework such as Moq or FakeItEasy. Each of the public members are virtual or settable and the class is not sealed. You should be able to mock using the same approach that you prefer for other types - whether with a mocking framework or inheriting from the class and creating your own mock type - and make use of the model factory to simulate behavior.

For ServiceBusReceivedMessage and other model types that are returned by service operations, the ServiceBusModelFactory is used to create instances for testing purposes.

Jesse Squire
  • 6,107
  • 1
  • 27
  • 30