Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NUnit and [SetUp] in base classes

Tags:

c#

nunit

I'm looking at some test code using NUnit, which inherits from a base class containing a [SetUp] attribute:

public class BaseClass {    [SetUp]    public void SetUp()    {      //do something    }  }  [TestFixture] public class DerivedClass : BaseClass {   [SetUp]   public void SetUp()   {     //do something else, with no call to base.SetUp()   }    //tests run down here.    //[Test]    //[Test]    //etc } 

The derived class will certainly need the work done in the base class' SetUp() method.

Am I missing something, or will the SetUp() method in the base class not be called when the derived class's tests are run? Is there something special with the [SetUp] attribute that ensures one will be called before the other?

like image 762
larryq Avatar asked Jul 15 '13 16:07

larryq


1 Answers

Before NUnit 2.5 the previous answers were correct; you could only have a single [SetUp] attribute for a test.

With NUnit 2.5 onwards you can have multiple methods decorated with the [SetUp] attribute. Therefore the below is perfectly valid in NUnit 2.5+:

public abstract class BaseClass {     [SetUp]     public void BaseSetUp()     {         Debug.WriteLine("BaseSetUp Called")     } }  [TestFixture] public class DerivedClass : BaseClass {     [SetUp]     public void DerivedSetup()     {         Debug.WriteLine("DerivedSetup Called")       }      [Test]     public void SampleTest()     {         /* Will output          *    BaseSetUp Called          *    DerivedSetup Called         */     } } 

When inheriting NUnit will always run the '[SetUp]' method in the base class first. If multiple [SetUp] methods are declared in a single class NUnit cannot guarantee the order of execution.

See here for further information.

like image 170
Luke Merrett Avatar answered Sep 19 '22 07:09

Luke Merrett