使用 NUnit 创建嵌套的 TestFixture 类

本文关键字:TestFixture 嵌套 NUnit 创建 使用 | 更新日期: 2023-09-27 18:37:08

我正在尝试根据特定场景将单元测试类划分为逻辑分组。 但是,我需要有一个将在整个测试中运行的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
    }
}

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

如何达到预期效果(测试范围)? 是否有我可以使用的扩展或 NUnit 的东西会有所帮助? 我宁愿在这个时候坚持使用NUnit,而不是使用像SpecFlow这样的东西。

使用 NUnit 创建嵌套的 TestFixture 类

您可以为测试创建一个抽象基类,在那里执行所有安装和拆卸工作。然后,您的方案继承自该基类。

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