Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SetUp in derived classes with NUnit?

Tags:

nunit

If I have the following code:

[TestFixture]
public class MyBaseTest
{
    protected ISessionManager _sessionManager;

    [SetUp]
    public void SetUp() { /* some code that initializes _sessionManager */ }
}

[TestFixture]
public class MyDerivedTest : MyBaseTest
{
    IBlogRepository _repository;

    [SetUp]
    public void SetUp() { /* some code that initializes _repository */ }

    [Test]
    public void BlogRepository_TestGoesHere() { /* some tests */ }
}

...NUnit doesn't call the base SetUp routine. This is expected, and I don't have a problem with it in itself. I can get the derived SetUp to call the base SetUp first, like this:

[TestFixture]
public class MyDerivedTest : MyBaseTest
{
    IBlogRepository _repository;

    [SetUp]
    public new void SetUp()
    {
        base.SetUp();
        /* some code that initializes _repository */
    }

This is ugly. If it was a constructor, I wouldn't have to.

I could use the "template method" pattern, and have the following:

public void MyBaseTest
{
    abstract void SetUp();

    [SetUp]
    public void BaseSetUp()
    {
        /* base initialization */
        SetUp(); // virtual call
    }
}

I'm not particularly fond of this, either.

What do you do when their test classes need SetUp, and they're derived from another class that also needs SetUp?

like image 878
Roger Lipscombe Avatar asked Feb 14 '09 11:02

Roger Lipscombe


1 Answers

You have to call the method directly.

   [SetUp]
   public void DerivedSetUp()
   {
      base.BaseSetUp();
      // Do something else
   }

Edit: I haven't tried it, but perhaps a partial method might work too. I'd prefer to do the above though.

Edit2: I've just tried using partial methods. It didn't work. Even if it did, I think it's still going to be easier to call the base class.

like image 73
Iain Holder Avatar answered Oct 11 '22 14:10

Iain Holder