Here's what I ended up doing for anyone that is interested.
I extended DropCreateDatabaseAlways<TContext>
and overrode the Seed method to populate my database with known test data that my unit tests can rely on.
public class MyDatabaseInitializer : System.Data.Entity.DropCreateDatabaseAlways<MyDbContext>
{
protected override void Seed(MyDbContext context)
{
// Add entities to database.
context.SaveChanges();
}
}
I then implemented an [AssemblyInitialize]
method which sets the database initializer.
[TestClass]
public class Global
{
[AssemblyInitialize]
public static void AssemblyInitialize(TestContext context)
{
System.Data.Entity.Database.SetInitializer(new MyDatabaseInitializer());
}
}
This sets the initializer for the database but does not actually run it. The intitializer is run in a [TestInitialize]
method I wrote which forces the database to be dropped, recreated and reseeded before each test.
[TestClass]
public class MyTestClass
{
[TestInitialize]
public void TestInitialize()
{
MyDbContext context = new MyDbContext();
context.Database.Initialize(true);
}
[TestMethod]
public void MyUnitTest()
{
Assert.IsTrue(true);
}
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…