在内存数据库中使用 Entity Framework 7 测试 ASP.NET 5

标签 testing asp.net-core entity-framework-core

我想了解我在测试期间注入(inject) Controller 的上下文,并修改数据库上下文的“内存中”版本中的数据。

所以 Controller 看起来像这样

[Route("api/[controller]")]
public class TestController : Controller
{
    private readonly TestContext _testContext;
    public TestController(TestContext testContext)
    {
        _testContext = testContext;
    }

    [HttpGet]
    public IActionResult Get()
    {
        return Ok(new { _testContext.Users });
    }
}

测试看起来像这样

public class SiteTests
{
    [Fact]
    public async Task GetIt()
    {
        var server = TestServer.Create(app => { app.UseMvc(); }, services =>
        {
            services.AddMvc();

            services.AddEntityFramework()
            .AddSqlServer()
            .AddDbContext<TestContext>(options => options.UseInMemoryDatabase());

            services.AddScoped<TestContext, TestContext>();
        });

        var client = server.CreateClient();

        var response = await client.GetAsync("http://localhost/api/test");
        var content = await response.Content.ReadAsStringAsync();

        Assert.True(response.IsSuccessStatusCode);
    }
}

我很想在客户端收到请求之前以某种方式获取上下文并修改将从数据库上下文返回的数据。

我有测试project在 GitHub 上

最佳答案

如果您的目标是 .NET Core,您将无法使用任何自动模拟框架。

您能做的最好的事情就是将 TestContext 中的所有方法虚拟化,然后在您的单元测试中扩展它。

public class IntegrationTestContext : TestContext
{
    // override methods here
}

然后你可以使用

var context = new IntegrationTestContext();
services.AddInstance<TestContext>(context);

您还可以在 IntegrationTestContext 中捕获您想要的任何额外信息,并从您的测试中访问它。

关于在内存数据库中使用 Entity Framework 7 测试 ASP.NET 5,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34190361/

相关文章:

c# - Entity Framework Core 添加迁移给出的值不能为空。 (参数 'connectionString')

.net - CLI 中 Entity Framework 核心的 -IgnoreChanges 开关等效于什么?

asp.net-core - 有没有办法将 ASP.NET Core 应用程序区域打包为 NuGet 包?

azure - 如何在单个应用程序服务上部署 aspnet core web api 和 aspnet webapi

c# - 为枚举创建通用的 dbset 列表

java - 需要关于用于学术研究的 Java 开源项目的推荐

c# - 为 XP、Win 7 和 Vista 开发——我需要单独测试 Vista 吗?

java - 接收 JMeter 需要 saveservice 属性文件才能继续错误

perl - 如何覆盖 $dbh 上的提交以进行测试?

c# - 具有多种实现的 .NET Core 3.1 中的依赖注入(inject)