【问题标题】:Why instantiate new DbContext for each step of test为什么要为每个测试步骤实例化新的 DbContext
【发布时间】:2019-10-07 18:48:43
【问题描述】:

Testing with SQLite 上的 Entity Framework Core 文档中,示例代码为测试的每个步骤实例化一个新的 DbContext。这样做有什么理由吗?

    // Copied from the docs:
    [Fact]
    public void Add_writes_to_database()
    {
        // In-memory database only exists while the connection is open
        var connection = new SqliteConnection("DataSource=:memory:");
        connection.Open();

        try
        {
            var options = new DbContextOptionsBuilder<BloggingContext>()
                .UseSqlite(connection)
                .Options;

            // Create the schema in the database
            using (var context = new BloggingContext(options))
            {
                context.Database.EnsureCreated();
            }

            // Run the test against one instance of the context
            using (var context = new BloggingContext(options))
            {
                var service = new BlogService(context);
                service.Add("http://sample.com");
                context.SaveChanges();
            }

            // Use a separate instance of the context to verify correct data was saved to database
            using (var context = new BloggingContext(options))
            {
                Assert.Equal(1, context.Blogs.Count());
                Assert.Equal("http://sample.com", context.Blogs.Single().Url);
            }
        }
        finally
        {
            connection.Close();
        }
    }

    // Why not do this instead:
    [Fact]
    public void Add_writes_to_database()
    {
        // In-memory database only exists while the connection is open
        var connection = new SqliteConnection("DataSource=:memory:");
        connection.Open();

        try
        {
            var options = new DbContextOptionsBuilder<BloggingContext>()
                .UseSqlite(connection)
                .Options;

            // Create the schema in the database
            using (var context = new BloggingContext(options))
            {
                context.Database.EnsureCreated();

                var service = new BlogService(context);
                service.Add("http://sample.com");
                context.SaveChanges();

                Assert.Equal(1, context.Blogs.Count());
                Assert.Equal("http://sample.com", context.Blogs.Single().Url);
            }
        }
        finally
        {
            connection.Close();
        }
    }

为什么不实例化一次上下文,然后在整个测试方法中使用该实例,如第二个代码示例所示?

【问题讨论】:

  • 如果您的测试连接到数据库,那么它就不是单元测试...它是一个集成测试
  • 好点,我编辑了标题
  • 其实第三次创作的cmets讲的

标签: c# entity-framework-core


【解决方案1】:

因为that's how contexts should be used。它们应该根据请求创建并处理掉。

一个实际的原因是确保您每次都返回数据源,而不是仅仅查看上下文中的状态。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-09-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-10
    • 2020-07-27
    相关资源
    最近更新 更多