Dot-Net

您是否使用 TestInitialize 或測試類建構子來準備每個測試?為什麼?

  • December 2, 2008

這個問題與使用 MSTest 在 Visual Studio 中進行單元測試有關(這很重要,因為 MSTest 的執行順序)。標記為 [TestInitialize] 的方法和測試類建構子都將在每個測試方法之前執行。

所以,問題是,你傾向於在這些領域做什麼?您是否避免在其中任何一個中進行某些活動?你的理由是什麼:風格、技術、迷信?

建構子只是語言提供的一種結構。每個測試框架似乎都有自己的受控生命週期“初始化”。您可能只會在使用建構子來改變您的本地人時遇到麻煩。

**MSTest:**您會為每個TestMethod. 這可能是唯一可以在建構子、初始化程序或測試方法中改變本地變數而不影響其他測試方法的情況。

public class TestsForWhatever
{
   public TestsForWhatever()
   {
       // You get one of these per test method, yay!
   }

   [TestInitialize] 
   public void Initialize() 
   {
       // and one of these too! 
   }

   [TestMethod]
   public void AssertItDoesSomething() { }

   [TestMethod]
   public void AssertItDoesSomethingElse() { }
}

**MSpec:**你只會得到一個你所有EstablishBecause斷言(It)。所以,不要在你的斷言中改變你的本地人。並且不要依賴於基礎上下文中本地人的突變(如果你使用它們)。

[Subject(typeof(Whatever))]
public class When_doing_whatever
{
   Establish context = () => 
   { 
       // one of these for all your Its
   };

   Because of = () => _subject.DoWhatever();

   It should_do_something;
   It should_do_something_else;
}

引用自:https://stackoverflow.com/questions/334515