[英]How to create sqlite database in unit test and remove it after all test from class done 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
I need to create db, add some file there and remove it after unit test class methods are done.我需要创建数据库,在其中添加一些文件,并在单元测试 class 方法完成后将其删除。
Looking at this tutorial: https://dotnetcorecentral.com/blog/sqlite-for-unit-testing-in-net-core/看这个教程: 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);
}
}
You create an inmemory db then you make sure the database is created, you add anything you want to check and then you can do any querys/asserts to check its working as expected.您创建一个内存数据库,然后确保创建了数据库,添加任何您想要检查的内容,然后您可以执行任何查询/断言来检查其是否按预期工作。
just create this method and use the "db" for other facts (tests).只需创建此方法并将“db”用于其他事实(测试)。 hope works for you..希望对你有用..
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.