2011-11-21 60 views
4

我有一個我正在使用的日誌解析器,而這個日誌解析器有一個定義任何日誌記錄存儲引擎(內存,數據庫等)的基本方法的接口ILogStore。這個想法是,開發人員和用戶可以通過MEF插件界面添加或刪除日誌存儲引擎。我該如何告訴mstest忽略基類中的測試而不是子類中的測試?

然而,爲了確認一個ILogStore實現可以正確地存儲,過濾和檢索日誌條目我創建了一個基類單元/集成/ API測試:

public class LogStoreBaseTests 
{ 
    protected ILogStore _store; 

    [TestMethod] 
    public void Can_Store_And_Retrieve_Records() { } 

    [TestMethod] 
    public void Can_Filter_Records_By_Inclusive_Text() { } 

    [TestMethod] 
    public void Can_Filter_Records_By_Exclusive_Text() { } 

    // etc... 
} 

我測試實施任務由做這樣的事情:

[TestClass] 
public class InMemoryLogStoreTests : LogStoreBaseTests 
{ 
    [TestInitialize] 
    public void Setup() 
    { 
     _store = new InMemoryLogStore(); 
    } 
} 

這個工程除了MSTest的通知,在基類中的方法有[TestMethod]但錯誤好,因爲該類沒有[TestClass],它不因爲它本身並不是有效的測試。

如何讓MsTest在不從子類運行時忽略這些方法?

回答

13

原來的MSTest有[Ignore]屬性。我將該屬性和[TestClass]屬性放置在我的基礎測試中,並且它正確地忽略了基本測試的測試方法,同時在子類下運行時使用基本測試方法

0

從未見過這種方法,當一個測試夾具繼承另一個......我建議考慮採用其他方法,而不是圍繞這些測試基礎設施進行工作。

考慮之一:

  1. 移動在一個類由[TestClass] OR
  2. 標記所有測試創建兩個完全獨立的試驗歸類所以它們將不被耦合和相互影響
+0

我*希望*它們互相影響,以確保所有ILogStore實現的核心功能在它們的行爲中是一致的,並且當需求改變了ILogStore檢索方法的意圖返回時,它被確認爲適用於所有實現的新需求。 – KallDrexx

2

不當然,如果你能告訴MS測試忽略某些測試,但你可以要求它不運行某些測試類別。

例如以下屬性使測試集成類

[AttributeUsage(AttributeTargets.Method, AllowMultiple = true)] 
    public class IntegrationTestAttribute : TestCategoryBaseAttribute 
    { 
     public IList<string> categories; 

     public IntegrationTestAttribute() 
     { 
      this.categories = new List<String> { "Integration" }; 
     } 

     public override IList<string> TestCategories 
     { 
      get 
      { 
       return this.categories; 
      } 
     } 
    } 

,你可以把它標記你的基類爲抽象,使你的測試中調用某些抽象方法的另一種方法,誰正在實施這樣的人你類將實現這些方法。

例如

[TestClass] 
public abstract class BaseUnitTest 
{ 
    public BaseUnitTest(){} 
    private TestContext testContextInstance;   
    public TestContext TestContext 
    { 
     get 
     { 
      return testContextInstance; 
     } 
     set 
     { 
      testContextInstance = value; 
     } 
    }   
    [TestMethod] 
    public void can_run_this_test_for_each_derived_class() 
    { 
     Assert.IsNotNull(this.ReturnMeSomething()); 
    } 
    protected abstract string ReturnMeSomething(); 
} 

[TestClass] 
public class Derived1 : BaseUnitTest 
{ 

    protected override string ReturnMeSomething() 
    { 
     return "test1"; 
    } 
} 

[TestClass] 
public class Derived2 : BaseUnitTest 
{ 
    protected override string ReturnMeSomething() 
    { 
     return null; 
    } 
} 

另一種方法是使用AOP像MSTestExtension確實,代碼可以發現here

+1

哇,親愛的。不知道爲什麼我不認爲只是將基類標記爲抽象。這實際上可以做到,只需要在我回家時進行測試。 – KallDrexx

+0

只是將測試設置爲抽象不起作用。你如何告訴MSTest不要運行特定的類別? – KallDrexx

+0

在Visual Studio測試列表編輯器中,您可以按類別分組測試,我會在明天將答案與抽象派生類放在一起。 –

相關問題