Abstract Test Pattern

I thought now would be a good time to mention NUnitAddin's support for 'Abstract Tests'. Jonathan de Halleux has a good write up where he compares the Abstract Test Pattern with MbUnit's support for Composite Unit Testing.  I'm working with him to add support for MbUnit and will mention here when it's ready.  For the moment this is what you can do with plain old NUnit...

Let's say you wanted to test a number of different implementations of the IList interface.  Instead of writing tests for each implementation, you can create an abstract class containing all of the tests.  You then create concrete fixtures that implement a factory method for each implementation you want to test.

Once you have created your abstract tests, you can execute all tests in one of the concrete fixtures as per usual (by right clicking inside the body of the class and selecting 'Run Test(s)').  It is however more interesting to execute tests from inside the abstract base class.  This time if you select inside the body of the base class you will execute all tests in the concrete fixtures (in this case 6).  If you want to be more specific, you can target one of the test methods and have it executed for each concrete fixture.  Below you can see the 'TestAdd' method being targeted which, which causes the 'Add' method of both 'ArrayList' and 'StringCollection' to be tested (2 succeeded).

You can find build 0.6.350 of NUnitAddIn here under 'Latest File Releases'.

namespace Collections.Tests
{
   using System;
   using System.Collections;
   using System.Collections.Specialized;
   using NUnit.Framework;

   public class TestArrayList : BaseTestStringList
   {
       protected override IList CreateList()
       {
           return new ArrayList();
       }
   }

   public class TestStringCollection : BaseTestStringList
   {
       protected override IList CreateList()
       {
           return new StringCollection();
       }
   }

   [TestFixture]
   public abstract class BaseTestStringList
   {
       private IList list;

       [SetUp]
       public void SetUp()
       {
           this.list = CreateList();
       }
protected abstract IList CreateList(); [Test] public void TestAdd() { object item = Guid.NewGuid().ToString(); int beforeCount = this.list.Count; this.list.Add(item); Assert.AreEqual(beforeCount + 1, this.list.Count); } [Test] public void TestContains() { object item = Guid.NewGuid().ToString(); int beforeCount = this.list.Count; this.list.Add(item); Assert.IsTrue(this.list.Contains(item)); } [Test] public void TestClear() { object item = Guid.NewGuid().ToString(); this.list.Add(item); this.list.Clear(); Assert.AreEqual(0, this.list.Count); Assert.IsFalse(this.list.Contains(item)); } } }

1 Comment

Comments have been disabled for this content.