How to create SQLite database in unit test and remove it after all test from class done C# .net
I need to create db, add some file there and remove it after unit test class methods are done.
Looking at this tutorial: 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). 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();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With