簡體   English   中英

使用NUnit創建嵌套的TestFixture類

[英]Creating nested TestFixture classes with NUnit

我正在嘗試根據特定方案將單元測試類划分為邏輯分組。 但是,我需要有一個TestFixtureSetUpTestFixtureTearDown ,它將運行整個測試。 基本上我需要做這樣的事情:

[TestFixture]
class Tests { 
    private Foo _foo; // some disposable resource

    [TestFixtureSetUp]
    public void Setup() { 
        _foo = new Foo("VALUE");
    }

    [TestFixture]
    public class Given_some_scenario { 
        [Test]
        public void foo_should_do_something_interesting() { 
          _foo.DoSomethingInteresting();
          Assert.IsTrue(_foo.DidSomethingInteresting); 
        }
    }

    [TestFixtureTearDown]
    public void Teardown() { 
        _foo.Close(); // free up
    }
}

在這種情況下,我在_foo上得到一個NullReferenceException,大概是因為在執行內部類之前調用​​了TearDown。

如何實現預期的效果(測試范圍)? 是否有一個擴展或NUnit的東西,我可以使用,這將有所幫助? 我寧願堅持使用NUnit,也不要使用像SpecFlow這樣的東西。

您可以為測試創建抽象基類,在那里執行所有安裝和拆解工作。 然后,您的方案將從該基類繼承。

[TestFixture]
public abstract class TestBase {
    protected Foo SystemUnderTest;

    [Setup]
    public void Setup() { 
        SystemUnterTest = new Foo("VALUE");
    }

    [TearDown]
    public void Teardown() { 
        SystemUnterTest.Close();
    }
}

public class Given_some_scenario : TestBase { 
    [Test]
    public void foo_should_do_something_interesting() { 
      SystemUnderTest.DoSomethingInteresting();
      Assert.IsTrue(SystemUnterTest.DidSomethingInteresting); 
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM