gpt4 book ai didi

c# - CloudTableClient 单元测试

转载 作者:行者123 更新时间:2023-12-03 18:31:33 24 4
gpt4 key购买 nike

如何为依赖于 Azure 表存储的类编写单元测试,即 Microsoft.Azure.Cosmos.Table.CloudTableClient ?

我发现了这个 GitHub 问题,Azure Storage is still hard to unit test / mock ,但除了现在的方法之外我没有找到任何线索 virtual .
MyService依赖于 CloudTableClient并在内部获得对 CloudTable 的引用查询表。在我的示例中,我正在按分区和行键进行简单的查找:

public MyService(CloudTableClient tableClient
, ILogger<MyService> logger) { }

public async Task<MyMapping> GetMappingAsync(string rowKey)
{
var table = GetTable();
var retrieveOp = TableOperation.Retrieve<MyMapping>("MyPartitionKey", rowKey);
var tableResult = await table.ExecuteAsync(retrieveOp);
return tableResult.Result as MyMapping;
}

private CloudTable GetTable()
{
return tableClient.GetTableReference("FakeTable");
}

最佳答案

  • CloudTable 创建模拟
  • 覆盖 ExecuteAsync行为来自 Setup
  • CloudTableClient 创建模拟
  • 覆盖 GetTableReference返回 CloudTable 的行为模拟通过 Setup

  • using Moq;
    using Microsoft.Azure.Cosmos.Table;
    using Microsoft.Extensions.Logging;

    [TestInitialize]
    public void InitTest()
    {
    var cloudTableMock = new Mock<CloudTable>(new Uri("http://unittests.localhost.com/FakeTable")
    , (TableClientConfiguration)null); //apparently Moq doesn't support default parameters
    //so have to pass null here

    //control what happens when ExecuteAsync is called
    cloudTableMock.Setup(table => table.ExecuteAsync(It.IsAny<TableOperation>()))
    .ReturnsAsync(new TableResult());

    var cloudTableClientMock = new Mock<CloudTableClient>(new Uri("http://localhost")
    , new StorageCredentials(accountName: "blah", keyValue: "blah")
    , (TableClientConfiguration)null); //apparently Moq doesn't support default parameters
    //so have to pass null here

    //control what happens when GetTableReference is called
    cloudTableClientMock.Setup(client => client.GetTableReference(It.IsAny<string>()))
    .Returns(cloudTableMock.Object);

    var logger = Mock.Of<ILogger<MyService>>();
    myService = new MyService(cloudTableClientMock.Object, logger);
    }

    [TestMethod]
    public async Task HelloWorldShouldReturnANullResult()
    {
    //arrange
    var blah = "hello world";

    //act
    var result = await myService.GetMappingAsync(blah);

    //assert
    Assert.IsNull(result);
    }

    关于c# - CloudTableClient 单元测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58957600/

    24 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com