如何在单元测试中创建sqlite数据库,并在所有测试后从c# .net类中删除它



如何在单元测试中创建SQLite数据库并在所有测试完成后从c# .net类中删除它

我需要创建db,在那里添加一些文件,并在单元测试类方法完成后删除它。

看这个教程: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();
}

最新更新