DbContext.Database.EnsureCreated()

entity-framework-core xunit2

Question

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?

1
0
6/30/2017 5:08:12 AM

Accepted Answer

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.

0
6/30/2017 6:28:28 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow