Search code examples
c#nunittest-runner

nUnit SetupFixture class in C# not being called when tests are run


nUnit SetupFixture Reference

My Solution is setup like this, using SpecFlow Gherkin Features
Solution
- Tests Project
-- Features
-- Steps
- Pages Project
-- Pages

I run the nUnit test runner using a command like this:

"C:\Program Files (x86)\NUnit.org\nunit-console\nunit3-console.exe" ".\bin\Dev\Solution.dll"

And I've added this code into the steps folder of the project structure above.

using System;
using NUnit.Framework;

namespace TestsProject.StepDefinitions
{
    /// <summary>
    /// This class needs to be in the same namespace as the StepDefinitions
    /// see: https://www.nunit.org/index.php?p=setupFixture&r=2.4.8
    /// </summary>
    [SetUpFixture]
    public class NUnitSetupFixture
    {
        [SetUp]
        public void RunBeforeAnyTests()
        {
            // this is not working
            throw new Exception("This is never-ever being called.");
        }

        [TearDown]
        public void RunAfterAnyTests()
        {
        }
    }
}

What am I doing wrong? Why isn't the [SetupFixture] being called before all the tests begin by nUnit?


Solution

  • Use the OneTimeSetUp and OneTimeTearDown attributes for the SetUpFixture since you are using NUnit 3.0 instead of SetUp and TearDown attributes as detailed here.

    using System;
    using NUnit.Framework;
    
    namespace TestsProject.StepDefinitions
    {
        [SetUpFixture]
        public class NUnitSetupFixture
        {
            [OneTimeSetUp]
            public void RunBeforeAnyTests()
            {
                //throw new Exception("This is called.");
            }
    
            [OneTimeTearDown]
            public void RunAfterAnyTests()
            {
            }
        }
    }