简体   繁体   English

使用NUnit创建嵌套的TestFixture类

[英]Creating nested TestFixture classes with NUnit

I'm trying to partition a unit test class into logical groupings based on a specific scenario. 我正在尝试根据特定方案将单元测试类划分为逻辑分组。 However, I require to have a TestFixtureSetUp and TestFixtureTearDown that will run for the entire test. 但是,我需要有一个TestFixtureSetUpTestFixtureTearDown ,它将运行整个测试。 Basically I need to do something like this: 基本上我需要做这样的事情:

[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
    }
}

In this case I get a NullReferenceException on _foo presumably because the TearDown is being called before the inner class is executed. 在这种情况下,我在_foo上得到一个NullReferenceException,大概是因为在执行内部类之前调用​​了TearDown。

How can I achieve the desired effect (scoping of tests)? 如何实现预期的效果(测试范围)? Is there an extension or something to NUnit I can use that would help? 是否有一个扩展或NUnit的东西,我可以使用,这将有所帮助? I'd rather stick with NUnit at this time and not use something like SpecFlow. 我宁愿坚持使用NUnit,也不要使用像SpecFlow这样的东西。

You can create an abstract base class for your tests, do all the Setup and Teardown work over there. 您可以为测试创建抽象基类,在那里执行所有安装和拆解工作。 Your scenarios then inherit from that base class. 然后,您的方案将从该基类继承。

[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