如何在NUnit中每个测试会话只运行一次设置功能?

时间:2016-05-02 11:02:22

标签: c# nunit nunit-2.5

using NUnit.Framework;
using System;

namespace NUnitTest
{
    [SetUpFixture]
    public class GlobalSetup
    {
        static int test = 0;

        [SetUp]
        public void ImportConfigurationData ()
        {
            test++;
            Console.WriteLine (test);
        }
    }
}

如果我重复运行我的测试以及此全局设置功能(使用标准NUnit GUI runner),则每次打印的数字都会增加一。换句话说,每个测试会话都会运行多次此函数。

是否还有另一种方法可以让每个测试会话运行一次函数,或者这是跑步者的错误?

1 个答案:

答案 0 :(得分:1)

这是一种廉价的解决方法。

using NUnit.Framework;
using System;

namespace NUnitTest
{
    [SetUpFixture]
    public class GlobalSetup
    {
        // The setup fixture seems to be bugged somewhat.
        // Therefore we manually check if we've run before.
        static bool WeHaveRunAlready = false;

        [SetUp]
        public void ImportConfigurationData ()
        {
            if (WeHaveRunAlready)
                return;

            WeHaveRunAlready = true;

            // Do my setup stuff here ...
        }
    }
}
相关问题