研究EF & Code首先,前一段時間我問了一個問題(ref this thread),指導您如何防止測試互相重疊。我要種子數據庫,並在做它像這樣爲每個測試類(使用MSTest的):EF4.1 + Code First:交易測試
public class CustomerSmokeTests {
private const string CONNECTION_STRING = "server=localhost;database=CPT_CustomerDataSync_SmokeTests;uid=sa;pwd=Password1!;";
private DatabaseFactory _dbfactory;
private CustomerCacheContext _customerContext;
[TestInitialize]
public void Setup() {
// set initializer to create new DB
Database.SetInitializer(new SmokeTestCreateDbWithDataIfNotExists());
Database.SetInitializer(new SmokeTestDropCreateDbWithDataAlways());
// create new DB connection to local SQL Server
_dbfactory = new DatabaseFactory(CONNECTION_STRING);
// connect to DB to auto generate it
_customerContext = _dbfactory.GetDataContext();
}
[TestCleanup]
public void Cleanup() {
_customerContext.Dispose();
_dbfactory.Dispose();
}
// tests
}
但是這裏的問題是,每個測試創建/拆毀DB(因爲它們相互重疊不理想並失敗......如果你單獨運行測試,它們都會按照要求通過......這會大大減慢測試的速度)。
A good solution was to instead wrap them up in TransactionalScopes,但是我想確保在測試運行開始時,使用種子信息重新生成數據庫(因爲種子會在我的開發人員開發測試時發生變化)。
這樣做的蠻力方法是創建某種類型的處理程序,在測試init中,它將檢查數據庫是否最近創建,如果沒有,則使用種子信息創建它。如果沒有,它會忽略這一步。然後它會創建一個TransactionalScope(),它將在測試清理中回滾。
但是,有沒有更好的方法來處理這個問題?用這個蠻力appraoch得到了過度的工程感覺......想法?
實體框架已經在savechanges後面使用幕後交易 –