Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I need to create db, add some file there and remove it after unit test class methods are done.

like image 340
Jakub Gerlee Avatar asked Oct 26 '25 10:10

Jakub Gerlee


2 Answers

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.

like image 192
Jonese1234 Avatar answered Oct 27 '25 23:10

Jonese1234


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();
    }

like image 37
Shahab Attarnejad Avatar answered Oct 28 '25 00:10

Shahab Attarnejad