使用NUnit创建嵌套的TestFixture类

Way*_*ina 4 c# nunit unit-testing

我正在尝试根据特定方案将单元测试类划分为逻辑分组.但是,我需要有一个TestFixtureSetUp,TestFixtureTearDown这将运行整个测试.基本上我需要做这样的事情:

[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
    }
}
Run Code Online (Sandbox Code Playgroud)

在这种情况下,我得到一个NullReferenceException,_foo大概是因为在执行内部类之前调用​​了TearDown.

如何实现预期的效果(测试范围)?是否有一个扩展或NUnit的东西,我可以使用,这将有所帮助?我宁愿坚持使用NUnit,也不要使用像SpecFlow这样的东西.

Den*_*aub 7

您可以为测试创建抽象基类,在那里执行所有安装和拆解工作.然后,您的方案将从该基类继承.

[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); 
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 但是没有办法在“Given_some_scenario”类下嵌套另一个类吗?这个想法是让包含类相对于整个部分(例如“CustomerTests”),然后为各个场景创建每个子类(例如“When_searching_customers”) (2认同)