NUnit and [SetUp] in base classes

c#, nunit

Solution

You can only have one `SetUp` method.

A TestFixture can have only one SetUp method. If more than one is defined the TestFixture will compile successfully, but its tests will not run.

http://www.nunit.org/index.php?p=setup&r=2.2.10

If you need to add additional setup logic in a child class, mark `SetUp` as virtual in your parent class, override it, and call `base.SetUp()` if you want the base class's setup to run, too.

public class BaseClass
{
   [SetUp]
   public virtual void SetUp()
   {
     //do something
   }

}



[TestFixture]
public class DerivedClass : BaseClass
{
  public override void SetUp()
  {
   base.SetUp(); //Call this when you want the parent class's SetUp to run, or omit it all together if you don't want it.
   //do something else, with no call to base.SetUp()
  }
   //tests run down here.
   //[Test]
   //[Test]
   //etc
}

Problem

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?

Original source