2010-06-10 38 views
11

我想測試一個具有較高圈複雜度(嘆氣)的方法,並且我希望在測試類中有一個類,以便方法測試類顯示爲節點那個樹。如何與Nunit一起使用?Nunit:是否有可能使測試出現嵌套

MyEntityTests 
| 
L_ MyComplexMethodTests 
    L when_some_condition_than 
    L when_some_other_condition_than 

[TestFixture] 
public class MyEntityTests 
{ 
    [TestFixture] 
    public class MyComplexMethodTests 
    { 
    [Test] 
    public void when_some_condition_than() {} 
    etc..... 

    } 
} 
+0

你想通過嵌套測試來完成什麼? – Pedro 2010-06-30 13:44:15

+0

這個問題並不明顯嗎? – epitka 2010-06-30 20:44:53

+0

你想只運行一些測試,但不是其他人?你是否只需要將它們在視覺上分開? – Pedro 2010-07-28 19:36:44

回答

17

您可以使用嵌套類來完成它,與您問題中的示例代碼非常相似。

與您的代碼唯一的區別是,外部類不需要[TestFixture]屬性,如果它僅用於結構並且本身沒有測試。

也可以具有所有內部類共享Setup方法中,通過將其放入外部類和具有內部類從外類繼承:

using NUnit.Framework; 

namespace My.Namespace 
{ 
    public class MyEntityTests 
    { 
     [SetUp] 
     public void Setup() 
     { 
     } 

     [TestFixture] 
     public class MyComplexMethodTests : MyEntityTests 
     { 
      [Test] 
      public void when_some_condition_than() 
      { 
      } 

      [Test] 
      public void when_some_other_condition_then() 
      { 
      } 
     } 
    } 
} 

在NUnit的GUI,該測試類將看起來像這樣:

NUnit GUI

+3

Resharper的測試跑步者似乎認識到但忽略了以這種方式構建的任何測試。 :\ – 2014-02-24 00:42:58

+0

@JohnHoerr在較新版本的ReSharper中可以使用。 – 2015-10-29 08:59:27

+0

你知道內部類是否可以有一個額外的SetUp方法?那麼所有的類都可以發生類的全局設置,而特定於方法的設置可能發生在內部類中?沒關係,在這裏找到答案:https://stackoverflow.com/questions/17659213/nunit-and-setup-in-base-classes – IronSean 2017-07-06 13:32:36

1

這聽起來像你有一個類要測試,但你有兩組/類型的測試運行。最簡單的方法可能是創建兩個TestFixture,每個都有一個。另一種方法是將每個測試放入一個類別中。

編輯:如果所有的測試都採用相同的方法,則一個選項是使用TestCase屬性並指定每個測試的參數(以及預期結果)。GUI將嵌套每組TestCase參數在該測試名稱的單個實例下。這假設你所有的測試都會有相似的行爲,這意味着相同的基本Asserts或ExpectedExceptions。

6

我用命名空間來得到這個行爲(濫用):

namespace MyEntityTests.MyComplexMethodTests 
{ 
    [TestFixture] 
    public class when_some_condition_than 
    { 
     [Test] 
     public void it_should_do_something() 
     {   
     } 
    } 

    [TestFixture] 
    public class when_some_other_condition_than 
    { 
     [Test] 
     public void it_should_do_something_else() 
     {   
     } 
    } 
} 

,這將給你:

MyEntityTests 
- MyComplexMethodTests 
    - when_some_condition_than 
    - it_should_do_something 
    - when_some_other_condition_than 
    - it_should_do_something_else 

在這種情況下,我會正常使用的TestFixture定義測試的上下文。

+0

+1 - 我目前的需求很好的解決方案。 – JOpuckman 2012-06-20 00:06:14

相關問題