模拟 IDynamoDBContext.ScanAsync 方法

问题描述 投票:0回答:1

我正在尝试为下一个方法创建单元测试:

     public async Task<Entity> GetEntityByIdAsync(Guid id)
     {
        List<ScanCondition> scanConditions = new List<ScanCondition>();

        scanConditions.Add(new ScanCondition("Date", ScanOperator.Between, GetDayRange(submitDate).Item1, GetDayRange(submitDate).Item2));
        scanConditions.Add(new ScanCondition("FieldId", ScanOperator.Equal, id));

        List<Entity> data = await _dynamoDbContext.ScanAsync<Entity>(scanConditions).GetRemainingAsync().ConfigureAwait(false);

        return data.OrderByDescending(r => r.SubmitDate).FirstOrDefault();  
    }

我为 IDynamoDBContext 创建了 Mock,但 ScanAsync 方法的设置有问题。

有人有什么想法吗?

谢谢!

c# unit-testing mocking amazon-dynamodb xunit
1个回答
0
投票

您无法创建 AsyncSearch 的实例,因为没有可用的构造函数,但您可以模拟对象本身。

var mockContext = new Mock<IDynamoDBContext>();
var mockData = new List<YourModel> { /* populate your fields */ };


var mockAsyncSearch = new Mock<AsyncSearch<YourModel>>();
mockAsyncSearch.Setup(search => search.GetRemainingAsync(It.IsAny<CancellationToken>()))
               .ReturnsAsync(mockData);


mockContext.Setup(context => context.ScanAsync<YourModel>(It.IsAny<List<ScanCondition>>(), It.IsAny<DynamoDBOperationConfig>()))
           .Returns(mockAsyncSearch.Object);



var result = await _sut.GetEntityByIdAsync(Guid.NewGuid());
© www.soinside.com 2019 - 2024. All rights reserved.