简体   繁体   中英

Unit Testing in Azure Functions RabbitMQ using xUnit Test

I did some googling based on how to do xUnit Test for Azure Functions, but the sample I saw was using HTTPRequest .

Is there a way of doing xUnit Test for RabbitMQ? This is my function:

    [FunctionName("MyFirstAzureFunction")]
    public static async void RabbitMQTrigger_MyFirstAzureFunction(
        [RabbitMQTrigger("MyFirstAzureFunction.Queue", ConnectionStringSetting = "ConnString")]string inputEvent, 
        [RabbitMQ(QueueName = "MyFirstAzureFunction.Queue", ConnectionStringSetting = "ConnString")]IAsyncCollector<string> outputEvent,
        ILogger log)
    {
        //SOME FUNCTION HERE
        return
        }
        catch (Exception ex)
        {
            await outputEvent.AddAsync(inputEvent);
        }
    }

As mentioned in a comment, you can mock the IAsyncCollector using Moq to verify whether the .AddAsync() method was called in your catch block with the expected input:

[TestClass]
public class MyFirstAzureFunctionTests
{
    [TestMethod]
    public async Task GivenRabbitMQTrigger_WhenException_ThenInputEventAddedToOutputEventCollector()
    {
        // arrange
        var mockOutputQueue = new Mock<IAsyncCollector<string>>();
        var mockLogger = new Mock<ILogger>();

        var inputEvent = "foo";

        // act
        await MyFirstAzureFunction.Run(inputEvent, mockOutputQueue.Object, mockLogger.Object);

        // assert
        mockOutputQueue
            .Verify(x => x.AddAsync(It.Is<string>(s => s == inputEvent), It.IsAny<CancellationToken>()), Times.Once);
    }
}

My example uses MS Test but hopefully you get the idea.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM