繁体   English   中英

如何在单元测试中创建 sqlite 数据库并在 class 完成所有测试后将其删除 C# .net

[英]How to create sqlite database in unit test and remove it after all test from class done C# .net

如何在单元测试中创建 SQLite 数据库并在 class 完成所有测试后将其删除 C# .net

我需要创建数据库,在其中添加一些文件,并在单元测试 class 方法完成后将其删除。

看这个教程: https ://dotnetcorecentral.com/blog/sqlite-for-unit-testing-in-net-core/

[Test]
public void Test_Get_By_Id()
{
    var connection = new SqliteConnection("DataSource=:memory:");
    connection.Open();

    var options = new DbContextOptionsBuilder<EmployeeContext>().UseSqlite(connection).Options;

    using (var context = new EmployeeContext(options))
    {
        context.Database.EnsureCreated();
    }

    using (var context = new EmployeeContext(options))
    {
        context.Employees.Add(new Employee { Id = 1, FirstName = "John", LastName = "Doe", Address = "123 Street", HomePhone = "111-111-1111", CellPhone = "222-222-2222" });
        context.SaveChanges();
    }

    using (var context = new EmployeeContext(options))
    {
        var provider = new EmployeeProvider(context);
        var employee = provider.Get(1);

        Assert.AreEqual("John", employee.FirstName);
    }
}

您创建一个内存数据库,然后确保创建了数据库,添加任何您想要检查的内容,然后您可以执行任何查询/断言来检查其是否按预期工作。

只需创建此方法并将“db”用于其他事实(测试)。 希望对你有用..


    private ApplicationDbContext GetContext()
    {
        var options = new DbContextOptionsBuilder().
            UseSqlite("Data Source = nameOfYourDatabase.db")
            .Options;

        var db = new ApplicationDbContext(options);

        db.Database.EnsureDeleted();
        db.Database.EnsureCreated();

        return db;
    }

    [Fact]
    public void CreateDatabaseTest()
    {
        using var db = GetContext();
    }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM