How to have a setup function only run once per test session in NUnit?

2.1k views Asked by At
using NUnit.Framework;
using System;

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

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

If I repeatedly run my tests along with this global setup function (using the standard NUnit GUI runner), the number that is printed increases by one each time. In other words, this function is run multiple times per test session.

Is there another way to really have a function run once per test session, or is this a bug in the runner?

1

There are 1 answers

1
chtenb On

This is a cheap workaround.

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 ...
        }
    }
}