You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用XUnit和Moq测试DynamoDB遇空引用异常,求解决方案

Mock AWS DynamoDB .NET客户端时遭遇空引用异常

我正在为对接AWS DynamoDB的.NET 6应用编写数据访问层(DAL),采用文档模型实现,AWS端配置已完成,需要编写单元测试与集成测试。

我尝试以TDD模式编写单元测试,但在Mock DynamoDB客户端时遇到困难。没找到Mock DynamoDB的有效方案,只见过使用本地DynamoDB的案例,但我不想用这种方式——这不符合单元测试的定义,而且测试需要在DevOps构建流水线中独立运行。

以下是我的尝试代码,但客户端获取表描述时出现**“对象未设置为实例”的空引用异常**,我陷入了困境,恳请帮助:

[Fact]
public void Get_WithValidId_ReturnsEntity()
{
    var mockDynamoClient = new Mock<IAmazonDynamoDB>();
    
    var describeTableResponse = new DescribeTableResponse
    {
        Table = new TableDescription
        {
            TableName = "TestTable"
        },
        HttpStatusCode = HttpStatusCode.OK
    };

    // 尝试两种不同方式获取表描述
    mockDynamoClient
        .Setup(s => s.DescribeTableAsync(It.IsAny<string>(), It.IsAny<CancellationToken>()))
        .ReturnsAsync(describeTableResponse);

    mockDynamoClient
        .Setup(s => s.DescribeTableAsync(It.IsAny<DescribeTableRequest>(), It.IsAny<CancellationToken>()))
        .ReturnsAsync(describeTableResponse);

    var repo = new DynamoRepository(mockDynamoClient.Object);

    var result = repo.Get(3);

    result.Should().NotBeNull();
}

错误:Object reference not set to an instance of an object.

堆栈跟踪:

at Amazon.DynamoDBv2.DocumentModel.Table.DescribeTable(String tableName)
   at Amazon.Runtime.Internal.Util.Cache`2.GetValueHelper(TKey key, Boolean& isStaleItem, Func`2 creator)
   at Amazon.Runtime.Internal.Util.Cache`2.GetValue(TKey key, Func`2 creator, Boolean& isStaleItem)
   at Amazon.DynamoDBv2.DocumentModel.Table.LoadTableInfo()
   at Amazon.DynamoDBv2.DocumentModel.Table.LoadTable(IAmazonDynamoDB ddbClient, TableConfig config)
   at Amazon.DynamoDBv2.DocumentModel.Table.LoadTable(IAmazonDynamoDB ddbClient, String tableName, DynamoDBEntryConversion conversion, Boolean isEmptyStringValueEnabled)
   at Amazon.DynamoDBv2.DocumentModel.Table.LoadTable(IAmazonDynamoDB ddbClient, String tableName)
   at MyApp.Infrastructure.Data.Repositories.DynamoRepository.Get(Int32 id) in C:\projects\MyApp\Infrastructure\Data\Repositories\DynamoRepository.cs:line 29

对应未完成的Get方法:

public async Task<Document> Get(int id)
{
    try
    {
        var table = Table.LoadTable(_dynamoDbClient, Constants.DynamoTableName);

        var item = await table.GetItemAsync(id);

        return item;
    }
    catch (Exception e)
    {
        Console.WriteLine(e);
        throw;
    }
}

内容的提问来源于stack exchange,提问作者CodeFirstAndy

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.12 15:50:18