5

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

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

我怎样才能达到预期的效果(测试范围)?我可以使用 NUnit 的扩展或其他东西来帮助吗?我现在宁愿坚持使用 NUnit,而不是使用 SpecFlow 之类的东西。

4

1 回答 1

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); 
    }
}
于 2012-06-12T18:58:42.090 回答