6

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?

jmbmage
  • 2,487
  • 3
  • 27
  • 44

1 Answers1

5

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()
        {
        }
    }
}
Jamleck
  • 1,017
  • 7
  • 12
  • 1
    Thanks! I finally got it to work by reading the link you shared and finding this: "A SetUpFixture outside of any namespace provides SetUp and TearDown for the entire assembly." – jmbmage Jun 16 '17 at 16:31
  • Putting the code in `namespace TestsProject` instead of `namespace TestsProject.StepDefinitions` works too. – jmbmage Jun 16 '17 at 16:40
  • 1
    Yes, both work. SetUpFixture is called to setup whatever namespace it is in and is run before and after every test in that namespace and below. This allows you to have multiple fixtures for different namespaces. – Rob Prouse Jun 17 '17 at 13:46