【问题标题】:How to have a setup function only run once per test session in NUnit?如何在 NUnit 中的每个测试会话中只运行一次设置功能?
【发布时间】:2016-05-02 11:02:22
【问题描述】:
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)重复运行我的测试,打印的数字每次都会增加一。换句话说,这个函数在每个测试会话中运行多次。

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

【问题讨论】:

    标签: c# nunit nunit-2.5


    【解决方案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 ...
            }
        }
    }
    

    【讨论】:

    • 对于 NUnit 3.4.1 及更高版本,请参阅this answer
    猜你喜欢
    • 2015-11-27
    • 2018-10-03
    • 2021-07-16
    • 1970-01-01
    • 1970-01-01
    • 2021-02-20
    • 1970-01-01
    • 1970-01-01
    • 2019-11-12
    相关资源
    最近更新 更多