簡體   English   中英

使用 XUNIT 進行 ServiceBusTrigger 單元測試

[英]ServiceBusTrigger Unit testing with XUNIT

我有一個 Azure 函數,如下所示。 在以下代碼中,我使用 Repository 和 EF Core 將產品添加到數據庫中。 有什么方法可以使用Xunit進行測試嗎? 目前,我正在使用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);
 }

用一個完整的例子來詳細說明 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")));
    }
}

您需要創建一個正在測試的類的實例並模擬依賴項。

Azure 函數本質上是類中的一個方法 ( .Run() ),您可以在實例上調用它。

在你的單元測試中,你創建數據來觸發方法,然后在你的模擬上做出斷言,當代碼真正運行時你期望發生什么。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM