'ServiceBusTrigger Unit testing with XUNIT

I have an Azure Function as below. In the following code, I'm adding a product to the database using Repository & EF Core. Is there any way we can test it using Xunit? Currently, I'm testing this using Azure Service Bus Explorer.

[FunctionName("SaveProductData")]
public void Run([ServiceBusTrigger("mytopicname", Connection = "ServiceBusConnectionString")]
ProductItemUpdate message, ILogger log)
{
    var product = new Domain.Entities.Product()
    {
       ... prop init goes here..... 
    };

    log.LogInformation($"Processed Product - Sain: {message.ProductId}");
    _productRepository.Add(product);
 }


Solution 1:[1]

To elaborate on scottdavidwalker's comment with a full example:

public class SaveProductDataTests
{
    private readonly Mock<IProductRepository> _mockProductRepository = new Mock<IProductRepository>();
    private readonly Mock<ILogger> _mockLogger = new Mock<ILogger>();

    private readonly SaveProductData _saveProductData;

    public SaveProductDataTests()
    {
        _saveProductData = new SaveProductData(_mockProductRepository.Object);
    }

    [Fact]
    public void Given_When_Then()
    {
        // arrange
        var productItemUpdate = new ProductItemUpdate();

        // act
        _saveProductData.Run(productItemUpdate, _mockLogger.Object);

        // assert
        _mockProductRepository.Verify(x => x.Add(It.Is<Product>(p => p.SomeProperty == "xyz")));
    }
}

You need to create an instance of the class you are testing and mock the dependencies.

The Azure function is essentially a method (.Run()) inside the class which you can call on the instance.

In your unit test, you create the data to trigger the method and then make assertions on your mocks for what you expect to happen when the code runs for real.

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 Chris B