'Im not able to mock ServiceBusReceivedMessage and ServiceBusMessageActions

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



Solution 1:[1]

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, 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.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1