asp.net-core - 无法为在 xUnit 中执行 Entity Framework Core 操作的控制器运行测试
问题描述
我无法为在 xUnit 中执行 Entity Framework Core 操作的控制器运行测试。我正在使用内存数据库,我得到的错误是:
**A test class may only define a single public constructor.**
测试类是:
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using MyAppT.Controllers;
using MyAppT.Models;
using Xunit;
namespace TestingProject
{
public class TestRegistration
{
#region Seeding
protected TestRegistration(DbContextOptions<AppDbContext> contextOptions)
{
ContextOptions = contextOptions;
Seed();
}
protected DbContextOptions<AppDbContext> ContextOptions { get; }
private void Seed()
{
using (var context = new AppDbContext(ContextOptions))
{
context.Database.EnsureDeleted();
context.Database.EnsureCreated();
var one = new Register()
{
Name = "Test One",
Age = 40
};
var two = new Register()
{
Name = "Test Two",
Age = 50
};
var three = new Register()
{
Name = "Test Three",
Age = 60
};
context.AddRange(one, two, three);
context.SaveChanges();
}
}
#endregion
[Fact]
public void Test_Create_GET_ReturnsViewResultNullModel()
{
using (var context = new AppDbContext(ContextOptions))
{
// Arrange
var controller = new RegistrationController(context);
// Act
var result = controller.Create();
// Assert
var viewResult = Assert.IsType<ViewResult>(result);
Assert.Null(viewResult.ViewData.Model);
}
}
}
}
执行 EF 核心操作的控制器是:
using Microsoft.AspNetCore.Mvc;
using MyAppT.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace MyAppT.Controllers
{
public class RegistrationController : Controller
{
private AppDbContext context;
public RegistrationController(AppDbContext appDbContext)
{
context = appDbContext;
}
public IActionResult Create()
{
return View();
}
[HttpPost]
public async Task<IActionResult> Create(Register register)
{
if (ModelState.IsValid)
{
context.Add(register);
await context.SaveChangesAsync();
return RedirectToAction("Read");
}
else
return View();
}
}
}
运行测试时出现的奇怪错误出现在测试资源管理器中 - 测试类只能定义一个公共构造函数。
我在stackoverflow上找不到任何关于它的信息。请帮忙修复一下?
解决方案
除非您在测试项目中使用某些 DI 框架,否则您的构造函数必须是无参数的,否则您通常不应该这样做。相反,请尝试在构造函数中创建 DBContextOptions 并将其分配给您的类变量。然后,您可以在为数据库播种以及针对它进行测试时使用它。
试试这个。Microsoft.EntityFrameworkCore.InMemory
如果你还没有这个包,你需要将包添加到你的测试项目中。
public class TestRegistration
{
#region Seeding
public TestRegistration()
{
ContextOptions = new DbContextOptionsBuilder<AppDbContext>()
.UseInMemoryDatabase(databaseName: "Test")
.Options;
Seed();
}
推荐阅读
- cordova - Cordova ionic inappbrowser sdktargetversion 23 到 26 通过 Intent.getData() 暴露在应用程序之外
- linux - 无法从 Linux 服务器以无头模式运行 Robot Framework 测试 - WebDriverException
- javascript - 带有选定值但无法获取选定值的 Django 下拉 [onChange] 框
- ruby-on-rails - 单个服务器上的多个 Rails 应用程序(2 个单独的域) - puma 和 nginx
- php - Laravel 上的 Google Adsense 5+
- c# - ASP.NET Core 2 - AD 组未映射到安全角色
- matplotlib - 放大 Cartopy 正交图
- javascript - 如何隐藏按钮?
- node.js - Jenkins 在构建时是否缓存依赖项和 Docker 层?
- angular - Angular 应用程序两次下载捆绑的 JS,这是一个错误吗?