【问题标题】:Creating nested TestFixture classes with NUnit使用 NUnit 创建嵌套的 TestFixture 类
【发布时间】:2012-06-13 03:29:20
【问题描述】:

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

【问题讨论】:

    标签: c# unit-testing nunit


    【解决方案1】:

    您可以为您的测试创建一个抽象基类,在那里完成所有设置和拆卸工作。然后,您的场景从该基类继承。

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

    【讨论】:

    • 但是没有办法在Given_some_scenario 类下嵌套另一个类?想法是让包含类与整个部分相关(例如CustomerTests),然后为各个场景设置每个子类(例如When_searching_customers
    • 为什么不使用继承通过层次结构进行分组? When_searching_customers : CustomerTestBaseWhen_creating_a_customer : CustomerTestBase 等?
    • 这确实可行,现在我想想!谢谢!
    • 我认为这个问题值得更好的回答;并不是说这在很多情况下都不好,但是如果有一个明确的“是”或“否”会很好。如果您的测试有多个 Datapoint Source 的 pr 测试,并且您想要一些层次结构来对测试进行分组而不是展开的平面列表,那么嵌套 TestFixtures 是一个很好的功能。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-12-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多