【问题标题】:How to unit test AWS SDK DynamoDB .NET core 6?如何对 AWS SDK DynamoDB .NET core 6 进行单元测试?
【发布时间】:2022-10-25 00:00:46
【问题描述】:

我遵循了有关使用 DynamoDB 作为数据库创建 Web API 的教程。现在我想编写单元测试,但我不知道怎么写,因为我没有存储库或存储库接口。 在另一篇文章中,我读到您可以模拟 DynamoDBContext 接口,但我仍然不知道从那里去哪里。

我的控制器

namespace FollowerService.Controllers;

[Route("api/[controller]")]
[ApiController]
public class FollowerController : ControllerBase
{
    private readonly IDynamoDBContext _context; //lets us use the DynamoDB
    private readonly IConfiguration _configuration;

    public FollowerController(IDynamoDBContext context, IConfiguration configuration)
    {
        _context = context;
        _configuration = configuration; 
    }

    [HttpGet]
    public async Task<IEnumerable<Follower>> GetAllFollowers(string userId)
    {
        var i = await _context.QueryAsync<Follower>(userId).GetRemainingAsync();
        return i;
    }


    [HttpPost]
    public async Task<IActionResult> AddFollower(Follower follower)
    {
        await _context.SaveAsync(follower);
        SQSProcessor sqsProcessor = new SQSProcessor(_configuration);
        await sqsProcessor.SQSPost(follower);
        //await SQSPost(follower);
        return Ok(follower);
        
    }

我的问题:我可以从一个可以测试 get 或 post 的好单元测试中获得一个示例吗? 如果出于任何原因我不需要为此控制器编写单元测试,也请告诉我原因

【问题讨论】:

  • 您的问题中没有包含实际的单元测试...似乎您没有努力提出有效的单元测试。所以问题是:你想在你的例子中测试什么?是控制器还是发电机上下文? PS:也许您还想使用存储库模式...这使您可以测试控制器独立于 DAL 的形式。 PPS:也许您应该在控制器中使用 DTO 而不是实体

标签: c# unit-testing amazon-dynamodb asp.net-core-6.0


【解决方案1】:

您只需在测试中模拟 dynamo db 上下文:

var userId = "xy";
var _context = Mock.Of<IDynamoDBContext>();
Mock.Get(_context)
    .Setup(x => x._context.QueryAsync<Follower>(userId))
    .ReturnsAsync(new Follower {UserId = userId});

但是,您可能还想编写组件测试。您可以使用 localstack 在本地启动 DynamoDb 以避免成本。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-01-06
    • 2018-05-08
    • 2018-10-26
    • 1970-01-01
    • 2020-07-28
    • 1970-01-01
    • 2023-01-04
    • 2012-08-11
    相关资源
    最近更新 更多