[英]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.