2009-06-07 59 views
0

我使用黃瓜普及的Given/When/Then風格編寫了一些C#集成測試。我正在使用一個基本上和NBehave一樣的框架。集成測試時設置系統狀態的最佳實踐/思路?

我面臨的經常性問題是設置和連接集成測試所需的所有應用程序狀態的問題。我的大多數測試是這個樣子:

 
Given an empty system 
    And a new NetworkServer 
    And a new ServerDatabase 
    And a new Eventlogger 
    And a new Networkconnection 
    And a new LoggingClient 
When the client logs a new event 
Then it should appear in the server database 

正如你所看到的行動,並斷言是單線條的,但我有6線「佈線」的。幾乎每個測試我都重複了這6條線。

這對我來說似乎是一種代碼味道,但我不確定如何處理這個問題。我可以將6行重構成一個(Given "a valid system..."或其他),但是這看起來太過分了,我會隱藏太多的信息。

我很感謝來自其他領域的更多經驗的任何想法。非常感謝。

回答

1

對我來說,這聽起來像你希望有一個基類做安裝類的東西,然後讓你的測試類從這個基地繼承,只添加新的測試功能。

Base(): 
    constructor(): 
    do your wiring 
    test if everything's ok 


TestClass : Base 
    constructor(): 
    Base.constructor() 
    additional setup? 

    test_functions() 
    .. 
+0

槽糕...感謝您的輸入。我必須承認我不喜歡基類模型,因爲它意味着一半的設置代碼隱藏在基礎構造函數中的完全不同的文件中......儘管如此,仍然看到不同的觀點。 +1 – 2009-06-08 21:23:43

1

我們有這樣的事情

public abstract class ContextSpecification 
{ 
    [FixtureSetUp] 
    public void SetUp() 
    { 
     EstablishContext(); 
     Act(); 
    } 

    protected abstract void Act(); 

    protected abstract void EstablishContext(); 

    [FixtureTearDown] 
    public void TidyUpCore() 
    { 
     TidyUp(); 
    } 

    protected virtual void TidyUp() 
    { 

    } 
} 

然後每個組的類似測試中,我們創建一個BaseContext這樣的:

internal class TestClassTests 
{ 
    internal abstract class BaseContext : ContextSpecification 
    { 
     protected TestClass _sut; 

     protected override void Act() 
     { 

     } 

     protected override void EstablishContext() 
     { 
      _sut = new TestClass(); 
      // common wiring 
     } 
    } 

    internal class Given_this_situation : BaseContext 
    { 
     protected override void EstablishContext() 
     { 
      base.EstablishContext(); 
      // test specific wiring 
     } 

     protected override void Act() 
     { 
      // carry out the test actions 
     } 

     [UnitTest] 
     public void ThisShouldBeTrue() 
     { 
      Assert.IsTrue(); 
     } 
    } 
} 
+0

有趣的是看到一個單獨的「行爲」方法,然後所有的斷言事後分開處理。你如何在實踐中發現這種工作?我認爲單元測試的目標之一是讓每個測試方法都是自治的(不依賴於之前運行的「Act」)... – 2009-06-08 21:25:06

+0

它工作得很好 - 我們傾向於將每個斷言放在自己的測試方法中,當測試中斷時傳達更多信息:我們不必尋找失敗的斷言。使用這種技術,我們簡單地將原理上移到層次結構中的一個層次 - 每個測試類都是自治的。 – 2009-06-09 08:14:47