C# - nunit / mstest相当于junit的@RunWith(HierarchicalContextRunner.class)

时间:2014-01-23 23:29:43

标签: c# unit-testing junit nunit mstest

我一直在关注单元测试教程并且代码是用java编写的,测试是层次化的,我不能将它们转换为c#而不知道nunit中的@RunWith(HierarchicalContextRunner.class)的等价物和/或mstest。

我一直在考虑继承,但我不确定这是正确的答案。

1 个答案:

答案 0 :(得分:0)

我不认为有办法在NUnit或MSTest中替换跑步者,但这是我使用NUnit的方式。

首先,您需要NUnit> = 2.5,以便SetUp方法从继承层次结构的顶部运行到当前测试类。然后:

public abstract class Given_An_Engine {
    protected Engine _engine;

    [SetUp]
    public void GivenAnEngine() {
        _engine = new Engine();
    }

    public abstract class That_Is_Stopped : Given_An_Engine {
        [SetUp]
        public void ThatIsStopped() {
            _engine.State = STOPPED;
        }

        public class When_I_Open_The_Status_UI : That_Is_Stopped {
            public StatusUI _ui; // You'll learn better ways than making _ui public. This is just for shortness.

            [SetUp]
            public void WhenIOpenTheStatusUI() {
              _ui = _engine.OpenUI();
            }

            [TestFixture]
            public class Behaves_Like_Display_Of_Stopped_Engine
                : Behaves_Like_Display_Of_Stopped_Engine<When_I_Open_The_Status_UI> {}
        }
    }
}

public class Behaves_Like_Display_Of_Stopped_Engine<TContext> 
    where TContext: Given_An_Engine.That_Is_Stopped.When_I_Open_The_Status_UI, new() {

    TContext ctx = new TContext();

    [SetUp]
    public void SetUp() {
        ctx.RunSetUp();
    }

    [TearDown]
    public void TearDown() {
        ctx.RunTearDown();
    }

    [Test]
    public void Displays_Stopped() {
       Assert.AreEqual("Stopped", ctx._ui.lblStatus.Text);
    }

    [Test]
    public void Displays_A_Red_Lamp() {
       Assert.AreEqual(Color.Red, ctx._ui.LampColor);
    }
}

RunSetUpRunTearDown方法是object上的扩展方法,您应该尝试自己编写,它们只有30行长。 RunSetUp应该从层次结构顶部向下运行所有​​SetUp方法到对象的类,而RunTearDown应该反过来。我把它作为锻炼给你。

RunSetUpRunTearDown也允许您撰写测试类。

public abstract Given_Two_Engines {
    protected Given_An_Engine engine1 = new Given_An_Engine.That_Is_Stopped();
    protected Given_An_Engine engine2 = new Given_An_Engine.That_Is_Stopped();

    [SetUp]
    public void GivenTwoEngines() {
        engine1.RunSetUp();
        engine2.RunSetUp();
    }

    [TearDown]
    public void UnGivenTwoEngines() {
        engine2.RunTearDown();
        engine1.RunTearDown();
    }

尝试一下,让我知道您对NUnit GUI中灯具的结果名称的看法。