5

特定のシナリオに基づいて、単体テスト クラスを論理グループに分割しようとしています。ただし、テスト全体で実行されるTestFixtureSetUpandが必要です。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
    }
}

この場合、_fooおそらく内部クラスが実行される前に TearDown が呼び出されているため、NullReferenceException が発生します。

目的の効果 (テストのスコープ) を達成するにはどうすればよいですか? 私が使用できる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 に答える