简体   繁体   English

使用 XUNIT 进行 ServiceBusTrigger 单元测试

[英]ServiceBusTrigger Unit testing with XUNIT

I have an Azure Function as below.我有一个 Azure 函数,如下所示。 In the following code, I'm adding a product to the database using Repository & EF Core.在以下代码中,我使用 Repository 和 EF Core 将产品添加到数据库中。 Is there any way we can test it using Xunit ?有什么方法可以使用Xunit进行测试吗? Currently, I'm testing this using Azure Service Bus Explorer .目前,我正在使用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);
 }

To elaborate on scottdavidwalker's comment with a full example:用一个完整的例子来详细说明 scottdavidwalker 的评论:

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. Azure 函数本质上是类中的一个方法 ( .Run() ),您可以在实例上调用它。

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.在你的单元测试中,你创建数据来触发方法,然后在你的模拟上做出断言,当代码真正运行时你期望发生什么。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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