2014-11-15 28 views
0

我是單元測試ASP MVC應用程序。現在我正在測試一個存儲庫。我有數據庫中的表,具有屬性ID(主鍵int),ItemName(varchar),IsValid(位 - 真/假)。 在存儲庫中,存在像使用單元測試(測試使用屬性isValid)進行測試的創建,更新,刪除等方法。還有一個方法getAllItems單元測試存儲庫。爲什麼DBContext返回錯誤的值?

public IEnumerable<Item> GetAllItems() 
{ 
return _db.ItemSet.Where(w => w.isValid); 
} 

運行創建,更新單元測試後,刪除還有一個單元測試方法,測試方法getAllWorkitem。

[TestMethod] 
    public void GetAllItems_Test() 
    { 
     //Arrange 
     var allWorkitems = _ws.GetAllItems(); 
     //Act 

     //Assert 
     foreach (Item currentItem in allItems) 
     { 
      Assert.AreEqual(true, currentItem.Valid); 
     } 

    } 

如果我單獨運行所有測試,它會正常工作。如果我一起運行所有測試,就會出現問題。 在var allWorkitems中有isValid = false和isValid = true的項目。

我認爲dbContext緩存查詢和數據以獲得更高的測試速度。有沒有posibitilies會禁用這種chaching。或者還有其他問題嗎?

+1

您是否在所有測試之間共享'_ws'對象? – DavidG

+0

是的,我做了一個dbContext。 – Fox

回答

0

在執行每個單元測試之前,您必須將測試的上下文設置爲乾淨狀態。我的意思是,你需要清除之前測試可能創建的任何數據,並清除下一個測試的路徑。

一種方法是使用測試設置方法,例如,

[TestInitialize] 
public void Setup() 
{ 
    // This function will be executed before each test. 
    // Use this function as an opportunity to clear any shared objects e.g. 
    // dbContext <- Delete all data that is not required. 
} 

[TestMethod] 
public void Test1() 
{ 
    // Arrange. 
    // Add 1 item to the dbContext 

    // Act 
    var actual = _ws.GetAllItems(); 

    // Assert. 
    Assert.AreEqual(1, actual.Count()); 
} 

[TestMethod] 
public void Test2() 
{ 
    // Arrange. 
    // Here, the dbContext will have been cleared in the Setup() function. 
    // Add 5 items to the dbContext 

    // Act 
    var actual = _ws.GetAllItems(); 

    // Assert. 
    Assert.AreEqual(5, actual.Count()); // Total items should be 5, not 6. 
} 

以上所有代碼都是假設的,我在飛行中完成了它。然而它確實說明了我的觀點,即在執行它們之前,您需要配置每個單元測試以使其處於預期狀態。

編輯:

基於您的評論,您的設置方法看起來是這樣的:

[TestInitialize] 
public void Setup() 
{ 
    _db = new MyIContainer(); 
    _ws = new ItemService(_db); 
} 

這樣一來,每個測試將有新的目標來工作,從之前的測試中沒有延遲的數據。

+0

聽起來很完美。那麼我應該怎麼做呢?我有私人靜態MyIContainer _db = new MyIContainer();和IItemService _ws = new ItemService(_db);我是否應該在註解[TestInitialize]的方法中重新使用它? – Fox

相關問題