Search code examples
entity-framework-corexunit2

DbContext.Database.EnsureCreated()


I am studying packtpub's entity framework core cookbook on unit test, there is an example (I made some change)

[Fact]
public void CanCreateDatabase()
{
    var blogContext = new BlogContext(_builder.Options);

    var created = blogContext.Database.EnsureCreated();

    Assert.True(created);
}

[Fact]
public void CanRetrieveRecord()
{
    var blogContext = new BlogContext(_builder.Options);

    var blog1 = blogContext.Blogs.FirstOrDefault();

    Assert.Contains("Development", blog1.Name);
}

The first test fail, the second pass. I am pretty sure the database has been created, that is why the second test passed, but why the first test fails?


Solution

  • Based on documentation of EnsureCreated here

    Returns
    System.Boolean
    True if the database is created, false if it already existed.

    In above tests, assuming there is no database present, for the first test run, EnsureCreated will create the database and pass the tests. But for any subsequent run, the database is already present hence EnsureCreated returns false. Perhaps you want to use EnsureDeleted before EnsureCreated to make sure that database is dropped so that you can test its actually being created.