Search code examples
c#.net-corec#-4.0azureservicebusazure-servicebus-subscriptions

How to mock ProcessMessageEventArgs object to pass as a parameter in a method from a test method in c#


I am writing a test method for below mention method -

Method in my concrete class -

public async Task ReadServiceBusMessage(ProcessMessageEventArgs args)
{
 // Some code

}

-- In my test method-

public async Test_ReadServiceBusMessage()
{
        private Mock<ProcessMessageEventArgs> _eventArgs;

        **_eventArgs = new Mock<ProcessMessageEventArgs>(MockBehavior.Strict);**

         await concreteClassObj.ReadServiceBusMessage(_eventArgs.Object);

}

this object creation (highighted in bold) is giving below exception message

Property ProcessMessageEventArgs.Message does not have a setter


Solution

  • You'll need to pass the message to the constructor. For example:

    Mock<ServiceBusReceiver> mockReceiver = new();
    
    mockReceiver
        .Setup(receiver => receiver.CompleteMessageAsync(
            It.IsAny<ServiceBusReceivedMessage>(),
            It.IsAny<CancellationToken>()))
        .Returns(Task.CompletedTask);
    
    ServiceBusReceivedMessage message = ServiceBusModelFactory.ServiceBusReceivedMessage(
            body: new BinaryData("message"),
            messageId: "messageId",        
            /* << SNIP for brevity, more fields available >> */
    );
    
    ProcessMessageEventArgs processArgs = new(
        message: message,
        receiver: mockReceiver.Object,
        cancellationToken: CancellationToken.None);
    

    More context and further examples can be found in the Mocking Client Types sample.