c# - 使用 InMemory 测试 ASP.NET Core API Controller

标签 c# testing asp.net-core controller in-memory-database

我正在尝试使用 InMemory 数据库而不是 SQL 服务器来测试 ASP.NET Core API Controller 。我也在使用 NUnit 来编写我的测试。在我的 SetUp 方法中,我创建了一些数据并添加到我的 InMemory 上下文中,这似乎工作正常,但是当我尝试使用我的 Controller 检索数据时,我得到了空值。

这是我的 Controller 的一部分:

public class PeopleController : ControllerBase
{
    private ApplicationDbContext _context;
    private IMapper _mapper;
    public PeopleController(ApplicationDbContext context, IMapper mapper)
    {
        _context = context;
        _mapper = mapper;
    }

    // GET /api/people
    [HttpGet]
    public IActionResult GetPeople()
    {
        return Ok(_context.People.ToList().Select(_mapper.Map<Person, PersonDto>));
    }
}

下面是我的测试课的一部分。当我调试测试时,我添加到 _context 的两个 Person 对象已正确添加,但是当我调用 _controller.GetPeople() 时,这两个对象没有显示,但我返回 null。使用我的 SQL Server,该方法“实时”运行良好。

[TestFixture]
class PeopleControllerTests
{
    private ApplicationDbContext _context;
    private IMapper _mapper;
    private PeopleController _controller;

    [SetUp]
    public void SetUp()
    {
        _mapper = GenerateConcreteInstance();

        var options = new DbContextOptionsBuilder<ApplicationDbContext>().UseInMemoryDatabase(databaseName: "TestDb").Options;
        _context = new ApplicationDbContext(options);

        _context.People.Add(new Person()
        { Id = 1, Firstname = "XXXXX", Lastname = "XXXXXXX", Email = "XXXX@XXXX.com", City = "XXXXX", DateCreated = DateTime.Now });
        _context.People.Add(new Person()
        { Id = 2, Firstname = "YYYYY", Lastname = "YYYYYYY", Email = "YYYY@YYYY.com", City = "YYYYY", DateCreated = DateTime.Now });
        _context.SaveChanges();

        _controller = new PeopleController(_context, _mapper);
    }

    [Test]
    public void GetAll_WhenCalled_ReturnPeopleInDb()
    {
        var result = _controller.GetPeople();

        var okObjectResult = result as OkObjectResult;
        var content = okObjectResult.Value as IEnumerable<Person>;
        Assert.IsNotNull(content);

    }

    private IMapper GenerateConcreteInstance()
    {
        var config = new AutoMapper.MapperConfiguration(c =>
        {
            c.AddProfile(new ApplicationProfile());
        });

        return config.CreateMapper();
    }
}

非常感谢任何帮助,因为我是 ASP.NET Core 和一般测试的新手!

最佳答案

您必须调用:

_context.SaveChanges()

在使用 _context.Add(T) 添加新条目时提交对数据库的更改。

关于c# - 使用 InMemory 测试 ASP.NET Core API Controller ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58418904/

相关文章:

authentication - 注销时应删除刷新 token 吗?

c# - 使用静态类来促进对应用程序设置的访问是否可以接受?

Django 测试没有运行特定的应用程序测试

java - Dagger 没有按预期覆盖模块

asp.net - 无法将索引 35 处的字节 [FC] 从指定的代码页转换为 Unicode

c# - 在 ASP.net API 核心 2.1 中向 JSON 输出添加部分

c# - 我无法使用 XmlSerializer 在 C# 中序列化对象列表

c# - 如何返回 FileStreamResult 列表

c# - 将 WPF View 分解为组件并维护数据绑定(bind)

performance - 如何提取URL中传递的值并将其用作Jmeter中的参数?