CloudTableClient 单元测试

spo*_*ahn 7 c# unit-testing moq azure-table-storage

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

我发现了这个 GitHub 问题,Azure Storage 仍然很难单元测试/模拟,但除了方法现在之外我没有找到任何线索virtual


MyService依赖CloudTableClient并在内部获取对 a 的引用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");
}
Run Code Online (Sandbox Code Playgroud)

spo*_*ahn 10

  1. 创建一个模拟 CloudTable
    • ExecuteAsync通过覆盖行为Setup
  2. 创建一个模拟 CloudTableClient
    • 覆盖GetTableReference行为以CloudTable通过以下方式返回模拟Setup
using Moq;
using Microsoft.Azure.Cosmos.Table;
using Microsoft.Extensions.Logging;
Run Code Online (Sandbox Code Playgroud)
[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);
}
Run Code Online (Sandbox Code Playgroud)
[TestMethod]
public async Task HelloWorldShouldReturnANullResult()
{
    //arrange
    var blah = "hello world";

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

    //assert
    Assert.IsNull(result);
}
Run Code Online (Sandbox Code Playgroud)