2011-12-05 85 views
5

我正在編寫一套集成測試(單元測試與MS測試,實體框架4.2是持續到數據庫正確的所有類)。實體框架集成測試DropCreateDatabaseAlways不清除測試之間的數據庫

當我逐個運行所有測試時,它們都可以正常工作。當我在一個組中運行它們時 - 它們中的一些失敗了,因爲返回的對象數量錯誤 - 看起來數據庫在測試開始時正在清理一次,而不是在每次測試之間清理 - 儘管我可以看到創建一個新的上下文,然後處理每個測試

任何想法?

public class EmptyDataInitializer : DropCreateDatabaseAlways<myContext> 
{ 
    protected override void Seed(myContext db) 
    { 
     //Do Nothing Create Empty Database 
     db.SaveChanges(); 
     base.Seed(db); 
    } 
} 

單位/集成的切割下來的版本測試

[TestClass] 
public class PersistanceTests 
{ 
    //Creating two instances of our Repository so that we can make sure that we are reading from our database rather than in-memory 
    private myContext _db; 
    private myContext _dbResults; 
    private readonly ISettings _configSettings; 

    public PersistanceTests() 
    { 
     _configSettings = MockRepository.GenerateStub<ISettings>(); 
     _configSettings.ConnectionString = "data source=.;initial catalog=myContext_Test; Integrated Security=SSPI; Pooling=false"; 

     Database.SetInitializer(new EmptyDataInitializer()); 
    } 

    //This is called a single time after the last test has finished executing 
    [TestCleanup] 
    public void TearDownTest() 
    { 
     _db.Dispose(); 
     _db = null; 
     _dbResults.Dispose(); 
     _dbResults = null; 
    } 

    //This is called each time prior to a test being run 

    [TestInitialize] 
    public void SetupTest() 
    {   
     _db = new myContext(_configSettings); 
     _dbResults = new myContext(_configSettings); 

     // This forces the database to initialise at this point with the initialization data/Empty DB 
     var count = _db.Accounts.Count(); 
     var resultCount = _dbResults.Accounts.Count(); 
     if (count != resultCount) throw new InvalidOperationException("We do not have a consistant DB experiance."); 
    } 
    [TestMethod] 
    public void OrganisationPersistanceTest() 
    { 
     // Arrange 
     var apple = new Organisation { Name = "Apple" }; 
     _db.Organisations.Add(apple); 
     // Act 
     _db.SaveChanges(); 
     var organisationsCount = _dbResults.Organisations.Count(); 
     var organisationsAppleCount = _dbResults.Organisations.Where(a => a.Id == apple.Id).Count(); 
     var result = _dbResults.Organisations.FirstOrDefault(a => a.Id == apple.Id); 
     // Assert 
     Assert.IsTrue(organisationsCount == 1, string.Format("Organisations Count Mismatch - Actual={0}, Expected={1}", organisationsCount, 1)); 
     Assert.IsTrue(organisationsAppleCount == 1, string.Format("Apple Organisations Count Mismatch - Actual={0}, Expected={1}", organisationsAppleCount, 1)); 
     Assert.IsNotNull(result, "Organisations Result should not be null"); 
     Assert.AreEqual(result.Name, apple.Name, "Name Mismatch"); 
    } 

    //A Unit test 
    [TestMethod] 
    public void OrganisationWithNumberOfPeople_PersistanceTest() 
    { 
     // Arrange 
     var person = new Person { Firstname = "Bea" }; 
     var anotherPerson = new Person { Firstname = "Tapiwa" }; 
     var apple = new Organisation { Name = "Apple" }; 
     apple.AddPerson(person); 
     apple.AddPerson(anotherPerson); 
     _db.Organisations.Add(apple); 
     // Act 
     _db.SaveChanges(); 
     var organisationsCount = _dbResults.Organisations.Count(); 
     var organisationsAppleCount = _dbResults.Organisations.Where(a => a.Id == apple.Id).Count(); 
     var result = _dbResults.Organisations.FirstOrDefault(a => a.Id == apple.Id); 
     var peopleCountInOrganisation = result.People.Count(); 
     // Assert 
     Assert.IsTrue(organisationsCount == 1, string.Format("Organisations Count Mismatch - Actual={0}, Expected={1}", organisationsCount, 1)); 
     Assert.IsTrue(organisationsAppleCount == 1, string.Format("Apple Organisations Count Mismatch - Actual={0}, Expected={1}", organisationsAppleCount, 1)); 
     Assert.IsNotNull(result, "Organisations Result should not be null"); 
     Assert.AreEqual(result.People.Count, peopleCountInOrganisation, "People count mismatch in organisation Apple - Actual={0}, Expected={1}", peopleCountInOrganisation, 2); 
     Assert.AreEqual(result.Name, apple.Name, "Name Mismatch"); 
    } 

}

步進通過測試,我可以看到SetupTest和TearDownTest方法被調用,但我也似乎沒有不在測試之間清理數據庫。

+0

好Dokey它似乎答案(儘管對我來說似乎有些ha is)是修改TestCleanup方法,以便在每次測試後明確刪除並重新創建數據庫 [TestCleanup] public v oid TearDownTest() if(_db.Database.Exists()) { _db.Database.Delete(); _db.Database.CreateIfNotExists(); } _db.Dispose(); _db = null; _dbResults.Dispose(); _dbResults = null; } –

+0

好吧,甚至更好的答案 - 添加一個database.Initialize(force:true); 納入TestInitialize方法。 [TestInitialize] public void SetupTest() { _db = new myContext(_configSettings); _db.Database.Initialize(force:true); –

回答

7

好的,甚至更好的答案 - 添加一個數據庫。inialialize(force:true); 納入TestInitialize方法。

[TestInitialize] 
public void SetupTest() 
{   
    _db = new myContext(_configSettings); 
    _db.Database.Initialize(force: true); 
    _dbResults = new myContext(_configSettings); 

    // This forces the database to initialise at this point with the initialization data/Empty DB 
    var count = _db.Accounts.Count(); 
    var resultCount = _dbResults.Accounts.Count(); 
    if (count != resultCount) throw new InvalidOperationException("We do not have a consistant DB experiance."); 
} 
+0

這與常規連接(非MDF)一起工作,你有一個提示,爲什麼當連接字符串包含'AttachDBFilename'參數時,相同的代碼將不起作用?在調用'.Initialize(true)'之後,EntityFramework會刪除指定路徑中的.MDF文件,但會拋出一個SQL異常,抱怨無法找到.MDF文件!這是否與我留下的恢復標誌/選項有關?這看起來像一個非常隨機的行爲對我來說! – Dr1Ku

1

我使用一個輔助做這種任務:

public abstract class TestingHelper 
{ 
     public static void ClearDatabase() 
     { 
      DatabaseContext myDbContext = new DatabaseContext(); 
      myDbContext.Database.Delete(); 
      myDbContext.Database.Create(); 
      //FillDatabase(lawyers); //<- OPTIONAL if you want to add rows to any type tables 
     } 
} 

,然後用它在你的測試設置:

[SetUp] 
public void MyTests_SetUp() 
{ 
     TestingHelper.ClearDatabase(); 
}