## Theory driven development using Microsoft Pex Explorer

EDIT: NOTE that some of the contents of this post have been recently been edited thanks to great feedback from Peli de Halleux (http://blog.dotnetwiki.org/). He pointed me at a great post on Test Driven Development with Parameterized Unit Tests that he’d wrote here: http://blog.dotnetwiki.org/TestDrivenDevelopmentWithParameterizedUnitTests.aspx

I’ve been playing with Microsoft Pex to try out some theory-driven development. I’ve found it a great tool – actually much better than I was hoping, it’s found more bugs, and test cases, than using just unit testing or TDD (Test-Driven Development). It’s test-driven development on steroids!

If you’ve been reading this blog, you’ll remember I blogged a while ago about TDD using theories, and what theories are – with the following posts:

http://taumuon-jabuka.blogspot.com/2008/03/theories.html

I mentioned that theories could have data-points generated by some sore of explorer, and Jeff Brown (http://blog.bits-in-motion.com/) one of the comments replied that maybe I could use Microsof Pex to do so, and I’ve found it to be perfect! A lot more powerful than I hoped.

This blog post will try to detail my experiences, but by far the best way to get to grips with this is to download Pex and try writing some theories!

In the example below, I’ll create a queue with the following operations:

Enqueue()

Dequeue()

Capacity

Count

It will have an initial capacity, and it will double in size once its capacity is exceeded (similar to the interface on .NET lists, for instance).

First, I’ll skip over a few tests written via TDD (a red-bar green-bar refactor cycle), before I get onto writing some theories.

First, in MSTest, we write a test.

        [TestMethod]        public void Test_NewlyConstructedQueue_CountIsZero()        {            Queue<int> queue = new Queue<int>();            Assert.AreEqual<int>(0, queue.Count);        }

Then we get the tests to compile, by implementing our queue with a Count property, such that we get a red bar, by getting the count property to return -1.

We then fix the test to get a green bar, but letting the Count return zero:

    public class Queue<T>    {        public int Count        {            get { return 0; }        }    }

We then introduce a test that default constructor creates stack with default stack of capacity 8.

        [TestMethod]        public void Test_ConstructDefaultConstructor_InitialCapacityIsEight()        {            Queue<int> queue = new Queue<int>();            Assert.AreEqual<int>(8, queue.Capacity);        }

The implementation is pretty simple:

        private const int initialCapacity = 8;        public int Capacity        {            get { return initialCapacity; }        }

Now, want to add a Dequeue method, and test that calling it on an empty stack throws an InvalidOperationException.

        [TestMethod]        [ExpectedException(typeof(InvalidOperationException))]        public void Test_NewlyConstructedQueue_DequeueThrowsException()        {            Queue<int> queue = new Queue<int>();            int i = queue.Dequeue();        }        public T Dequeue()        {            throw new InvalidOperationException("Should not call Dequeue on an empty queue");        }

We’re going to come back to look at this test shortly.

We add a test for Enqueue, to check its count is 1.

        [TestMethod]        public void Test_NewlyConstructedQueue_Enqueue_CountIsOne()        {            Queue<int> queue = new Queue<int>();            queue.Enqueue(1);            Assert.AreEqual(1, queue.Count);        }

Add an Enqueue method that does nothing to get this to compile and redbar. We actually have to add some implementation now, to get this to pass.

    public class Queue<T>    {        private const int initialCapacity = 8;        private T[] items = null;        public int Count        {            get { return items == null ? 0 : 1; }        }        public int Capacity        {            get { return initialCapacity; }        }        public T Dequeue()        {            throw new InvalidOperationException("Should not call Dequeue on an empty queue");        }        public void Enqueue(T item)        {            items = new T[initialCapacity];            items[0] = item;        }    }

There are lots of things wrong with this implementation – there are some obvious bugs, we’re recreating the array on each Enqueue, not to mention the array being a fixed size, with no capability to grow., and the weird Count implementation. This obviously needs implementing and refactoring, but it passes all our tests, and that’s TDD – we don’t go adding code until we drive it via adding more tests. So, lets add another couple of tests to drive the implementation:

        [TestMethod]        public void Test_NewlyConstructedQueue_Enqueue_DequeueReturnsItem()        {            Queue<int> queue = new Queue<int>();            queue.Enqueue(1);            int item = queue.Dequeue();            Assert.IsTrue(1 == item);        }

And can get the tests to pass with the following:

        public T Dequeue()        {            if (items == null)            {                throw new InvalidOperationException("Should not call Dequeue on an empty queue");            }            return items[0];        }

NOTE: We’re really taking baby steps, but to ensure that we’re not writing any untested implementation.

Now let’s add a test for adding and removing more than one item:

        [TestMethod]        public void Test_NewlyConstructedQueue_EnqueueTwoItems_DequeueReturnsFirstItem()        {            Queue<int> queue = new Queue<int>();            queue.Enqueue(1);            queue.Enqueue(2);            int item = queue.Dequeue();            Assert.IsTrue(1 == item);        }

To get this to pass we can more property implement our queue.

    public class Queue<T>    {        private int tailIndex = 0; // insertion        private int headIndex = 0; // removal        private const int initialCapacity = 8;        private T[] items = new T[initialCapacity];        public int Count        {            get { return tailIndex - headIndex; }        }        public int Capacity        {            get { return initialCapacity; }        }        public T Dequeue()        {            if (Count == 0)            {                throw new InvalidOperationException("Should not call Dequeue on an empty queue");            }            return items[headIndex--];        }        public void Enqueue(T item)        {            items[tailIndex++] = item;        }    }

To get this to work we had to add more and more example tests – we were saying quite general statements, but expressing this in more and more specific example cases, adding functionality as we went. This process is called triangulation (as I mentioned in an earlier blog post).

There are still a number of limitations here: if we exceed 8 items in the queue, we’ll get an IndexOutOfRange exception.

Can quite easily write a test for adding more values for the auto-growth.

Also, a more insiduous bug is that our values can migrate along the array – we’re not moving items back towards the back (or front of the queue), so could run out of space even with less than 8 values – a much harder bug to find. This is a subtle bug, and to find it using a unit test would be quite tricky, if you didn’t see it up front. USING PEX TO AUTOMATICALLY GENERATE THE THEORY VALIDATION IS GREAT FOR THESE TYPES OF BUGS!

Let’s see if we could have written our test in such a way that this problem may have been detected.

        [PexMethod]        public void Theory_CanAddRemoveAnyNumberOfItemsToNewlyConstructedQueue_IsEmptyAfterwards(int num)        {            Queue<int> queue = new Queue<int>();            for (int i = 0; i < num; i++)            {                queue.Enqueue(i);            }            for (int i = 0; i < num; i++)            {                queue.Dequeue();            }            Assert.AreEqual<int>(0, queue.Count);        }

Use the menu option “Run Pex Explorations”.

4 explorations (unit tests) are generated for this – passing in values of num 0, 1073741824, and 2 and 1.

0 passes.

1073741824 throws an IndexOutOfRangeException

2 throws an IndexOutOfRangeException

1 throws an AssertFailedException

This straight away shows that the code is more bugged than I thought. This would probably have been spotted on the introduction of further tests (for instance, test adding and removing three items from the list), but already highlights the power of theories.

Note: This could have been written as a unit test, but would have had to iterate over all possible integers, instead of just the 4 values that Pex provided.

Passing in a value of 1 – we had a similar test to this in enqueing and dequeing a single item, but we tested that the item dequeued was the same as that enqueued, we didn’t test the Count property.

This bug is due to the fact that the headIndex should have been incremented, instead of decremented on dequeuing.

Fixing that and running our tests (including the previously generated ones – without reexploring) results in 9 of the 10 tests passing. The failing case is we’re passing in a large in value.

This is obviously due to the fact that we’ve got a fixed size array, and it doesn’t auto-grow.

Let’s add an assumption to get our test to pass, before we go on to add the auto-grow functionality.

PexAssume.IsTrue(num <= queue.Capacity, "num is less than capacity");

In theories, assumptions allows us to state the input data for which the theory is valid.

We need to re-run the explorations so we’re not calling our test with data points that fail the assumption.

Before we go to get our queue to expand its capacity, let’s change our theory to see if it can detect the problem of running out of space after adding and removing items even before it goes out of capacity.

I originally wrote my theory in the format below, but see the second format and following comments, following feedback from Peli de Halleux.

        [PexMethod]        public void Theory_CanAddRemoveAnyNumberOfItemsAnyEmptyQueue_IsEmptyAfterwards(            [PexAssumeNotNull]Queue<int> queue, int num)        {            PexAssume.IsTrue(num <= queue.Capacity, "num is less than capacity");            PexAssume.IsTrue(queue.Count == 0);            for (int i = 0; i <= num; i++)            {                queue.Enqueue(i);            }            for (int i = 0; i <= num; i++)            {                queue.Dequeue();            }            Assert.AreEqual<int>(0, queue.Count);        }

This was rewritten to:

        [PexMethod]        [PexGenericArguments(typeof(int))]        public void Theory_CanAddRemoveAnyNumberOfItemsAnyEmptyQueue_IsEmptyAfterwards<T>(            [PexAssumeUnderTest]Queue<T> queue, [PexAssumeNotNull]T[] values)        {            PexAssume.IsTrue(values.Length <= queue.Capacity, "num is less than capacity");            PexAssume.IsTrue(queue.Count == 0);            for (int i = 0; i < values.Length; i++)            {                queue.Enqueue(values[i]);            }            for (int i = 0; i < values.Length; i++)            {                queue.Dequeue();            }            Assert.AreEqual<int>(0, queue.Count);        }

The PexAssumeNotNullAttribute states that the theory is not valid for null values of that parameter, but the PexAssumeUnderTest, as well as stating that the parameter cannot be null, gives Pex more hints for tuning its search strategies.

This is a much more general theory – we’re now saying given any empty queue, it will be empty after enqueueing and dequeueing.

We can instruct Pex how to construct a queue, that has had items added and removed:

        [PexFactoryMethod(typeof(Queue<int>))]        public static Queue<int> Create(int numberInitialAdds,            int numberInitialRemoves)        {            Queue<int> queue = new Queue<int>();            if (numberInitialAdds <= 0 || numberInitialRemoves < 0)            {                return queue;            }            for (int i = 0; i < numberInitialAdds; ++i)            {                queue.Enqueue(i);            }            int numberToRemove = numberInitialAdds > numberInitialRemoves ?            numberInitialRemoves : numberInitialAdds;            for (int i = 0; i < numberToRemove; ++i)            {                queue.Dequeue();            }            return queue;        }

Now, running the theory gives an IndexOutOfRangeException after adding and removing ight items to the queue in the factory – and then subsequently adding and removing one items. This should work – as we’re not exceeding the capacity.

This is powerful – if we were unaware of the existence of this bug it’s difficult to imagine how we would have come across it in TDD.

Let’s fix the failing theory before we remove our assumptions.

        public T Dequeue()        {            if (Count == 0)            {                throw new InvalidOperationException("Should not call Dequeue on an empty queue");            }            T item = items[headIndex++];            if (headIndex == tailIndex)            {                headIndex = tailIndex = 0;            }            return item;        }

Now, the tests run. Let’s go on to address the auto-grow issue.

Now, remove the assumption that values.Length <= queue.Capacity and re-explore this theory.

Get an index out of range exception when attempting an array of 15 items to the queue.

We can fix this by implementing auto-grow in the stack:

        public void Enqueue(T item)        {            if (tailIndex == items.Length - 1)            {                items = new T[items.Length * 2];            }            items[tailIndex++] = item;        }

We can now re-run our tests and they all pass.

Now, deleting all Generated Unit Tests in the class, and re-running Pex Explorations, gives Path bounds exceeded messages – the time is being spent in the factory adding and removing items to the queue, and exploring the paths of auto-growing the stack.

Instead of getting our queue into the required states by manipulating it via its public interface, we can more-directly construct it into any state.

        public Queue(T[] items, int headIndex, int tailIndex)        {            if ((uint)tailIndex >= (uint)(items.Length))                throw new ArgumentException("(uint)tailIndex >= (uint)(items.Length)");            this.items = items;            this.headIndex = headIndex;            this.tailIndex = tailIndex;        }

And instruct Pex to use this constructor with an assembly attribute:

[assembly: PexExplorableFromConstructor(typeof(Queue<int>),    typeof(int[]), typeof(int), typeof(int))]

Now, Pex is able to explore our theory, and finds no failing cases.

NOTE: In my original version of the theory, my theory took an int, the number of values to add to the queue, instead of the array of values, and it that case Pex would pass in a number of integers to add that would cause OutOfMemoryExceptions to occur. Instead, passing in the array of values means that Pex passes in more meaningful data.

The implementation of the queue is progressing; we’re autogrowing the stack, but we’re not copying the values across. We’re also not updating the capacity. We need to check that we can enqueue or dequeue items,and we’d obviously write more theories to do this.

This does show that the thought process behind writing theories is similar to TDD – the tests/theories are only as good as you write, and it’s still easy to miss obvious implentation (you still need to think about what you’re writing), but I feel that writing theories, with an explorer, allows many more bugs to be caught during the process. Hopefully this has given a good taste of theory driven development.

## Maslina and Rakija updates for NUnit 2.4.7

The above NUnit extensions have been updated, Rakija (the data-driven tests extension) has simply been rebuilt against NUnit 2.4.7.

Maslina (the theory extension) has had some changes.
Firstly, inline Assumptions have been added (i.e. you can Assume.IsTrue()) in the code.

The most important change, however, is that a failure of the pre-called assumptions now results in the body of the theory method not being called, i.e. theories are no longer validated (and similarly, Assume.IsTrue() exits the theory method immediately).

There were some very interesting discussions on the NUnit developer list recently which persuaded me of the error of my ways, most specifically, it can be too ‘dangerous’ to continue execution of a theory if the user has signalled that the data is invalid.

You should validate that your assumptions are valid when writing theories, but this should be done in either another theory, or plain vanilla unit test.

## Comparing Theories to more traditional testing

My old work colleague Tim has recently blogged about using NSpec to specify a stack.

NSpec has the same sort of functionality as a unit testing framework such as NUnit. The terminology has been changed to get over the roadblock that some people have in adopting tests.

Theories actually give something over and above normal unit testing, and that’s what I’m going to look at in this blog post. I’m going to look at Tim’s example and show how using theories actually differ from Tim’s more traditional example.

The stack interface for which the implementation was arrived at via speccing is as follows:

public class Stack<t>{public Stack();public void Clear();public bool Contains(T item);public T Peek();public T Pop();public void Push(T item);// Propertiespublic int Count { get; }}

The following tests were arrived at:

namespace Stack.Specs{[Context]public class WhenTheStackIsEmpty{    Stack _stack = new Stack<int>();    [Specification]    public void CountShouldBeZero()    {        Specify.That(_stack.Count).ShouldEqual(0);    }    [Specification]    public void PeekShouldThrowException()    {        MethodThatThrows mtt = delegate()           {               _stack.Peek();           };        Specify.ThrownBy(mtt).ShouldBeOfType(typeof(InvalidOperationException));    }}}

That’s ample for us to discuss the difference between theories and more normal testing.

For the PeekShouldThrowException test/specification, we can see from the naming of the context that the developer intends to show that for an empty stack, the Peek operation throws an exception. However, what the developer has actually shown is that calling Peek on a newly-created stack throws an exception.

Developers tend to think in fairly general terms, and express this generality by using more specific cases. However, some of this generality can get lost. Theories aim to keep more of that generality.

We can demonstrate this in a theory (don’t take much note of the syntax, just the concepts)

 [Theory] public void PeekOnEmptyStackShouldThrow(Stack<int> stack) {     try     {         stack.Peek();         Assert.Fail(ExpectedExceptionNotThrown);     }     catch (InvalidOperationException) { } }

This states that calling Peek() on ANY stack should fail, we need to show that this is only true for an empty stack. We could do this by simply checking for this:

 [Theory] public void PeekOnEmptyStackShouldThrow(Stack<int> stack) {     try     {         if (stack.Count == 0)         {             stack.Peek();             Assert.Fail(ExpectedExceptionNotThrown);         }     }     catch (InvalidOperationException) { } }

But as we’ll see in a bit, using assumptions gives us some extra feedback (again, don’t focus on the syntax).

 [Theory] [Assumption("AssumeStackIsEmpty")] public void PeekOnEmptyStackShouldThrow(Stack<int> stack) {     try     {         stack.Peek();         Assert.Fail(ExpectedExceptionNotThrown);     }     catch (InvalidOperationException) { } } public bool AssumeStackIsEmpty(Stack<int> stack) {     return stack.Count == 0; }

This is a much more general statement than the original specification/test, we’re saying that the stack should fail if we try to Peek on it for ANY empty stack.

We don’t care whether this is a newly-created stack, or it is a stack which has been manipulated via its public interface. Also, Liskov Substitution Principle states that we should be able to use any classes derived from Stack, and the theories should hold true.

We validate this theory with example data, in much the same way as when we’re doing test-driven development. The extra power comes from the generality in the way that the theory is written – we can imagine a tool that performs static code analysis on the Stack class to confirm that it obeys this.

However, the literature mentions that the most likely way to validate a theory is via an exploration phase, via a plug-in tool that will try various combinations of input data to look for anything that fails the theory.

It is prohibilively expensive to explore every possible combination of inputs, imagine all the possible values of a double, or in our example, there are an infinite number of operations that could happen to a stack that gets passed in.

This fits in nicely with the name theory with parallels with science – it’s not feasible to prove it, but we look for data to disprove it.

The example data is important for the red-green-refactor cycle. The exploration phase sits outside that – it finds which input data doesn’t fit the theory, allowing the theory to be modifed. There are exploration tools in Java, and I haven’t looked too much into it, but it may be possible to use Microsoft’s Pex as an exploration tool?

Before I forget, this is a possible way to specify the example data for our stack:

  [Theory]  [Assumption("AssumeStackIsEmpty")]  [InlineData("EmptyStack", new Stack())]  [PropertyData("EmptiedStack")]  public void PeekOnEmptyStackShouldThrow(Stack<int> stack)  {      try      {          stack.Peek();          Assert.Fail(ExpectedExceptionNotThrown);      }      catch (InvalidOperationException) { }  }  public List<exampledata> EmptiedStack  {      get      {          List<exampledata> data = new List<ExampleData>();          Stack stack = new Stack();          stack.Push(2);          stack.Push(3);          stack.Pop();          stack.Pop();          data.Add(stack);          return data;      }  }

In my prototype extension, the assumptions are important and are validated, as they tell us something vital about the code. I think that all the information about the behaviour of the system is vital, and should be documented and validated, but there are varied opinions on the list. That’s why I’m blogging – give me your feedback 🙂

If the user changed the behaviour of Peek() such that it was valid on an empty stack (it may return a Null Object for certain generic types), then our assumption would not detect this if it was simply filtering the data – the assumption would say “Peek() fails, but only on empty stacks”, whereas Peek() would not fail on empty stacks. See my previous post for the behaviours I have implemented.

Notice in Tim’s implementation how his stack is hardcoded to have at most 10 items. When TDDing we may make slightly less obviously limited implementations to get our tests to pass, but forget to add the extra test cases to show this limitation (the process of progressively adding more and more general test cases is called triangulation).

When writing theories, the same process happens, but writing the theories as a more general statement means that a code reviewer/automated tool can see that the developer intended that we intended that we can push a new item onto ANY stack, not just a stack that contained 9 or less items.

Any thoughts? Have I got the wrong end of the stick? If anyone found this post useful, I might full flesh out the equivalent of Tim’s example.

## Sample Theory Implementation as NUnit Extension.

There’s been lots of comments bouncing around on the NUnit mailing list about what exactly constitutes a Theory, and what the desired features are, so I’ve created an NUnit extension with a sample Theory implementation – you can get it, Maslina version 1.0.0.0, from www.taumuon.co.uk/rakija

xUnit.Net implements theories but does not have any in-built Assumption mechanism (you can effectively filter out bad data, which is the same as a filtering assumption). JUnit 4.4, I think, only filters out data – it doesn’t tell us anything about the state of an assumption.

Anyway, from reading the literature on theories (see my previous blog posting), I quite like the idea of having assumptions tell us something about the code, that those assumptions are validated.

The syntax of my addin is quite poor, and there’s not really enough validation of user input, but I’m aiming to try to do some theory-driven development (theorizing?) using it, to see what feels good and what grates.

Any feedback gratefully received (especially – is it valid to say that this is an implementation of a Theory, are validation of assumptions useful or unnecessary fluff?)

Here is the syntax of my extension.

 [TestFixture] public class TheorySampleFixture {     [Theory]     [PropertyData("MyTestMethodData")]     [InlineData("Parity", new object[] { 1.0, 1.0, 1.0 })]     [InlineData("Parity 2", new object[] { 2.0, 2.0, 1.0 })]     [InlineData("Double Euros", new object[] { 2.0, 1.0, 2.0 })]     // This does not match the assumption, and will cause this     //specific theory Assert to fail, in which case we will get a pass overall.     // If the unit under test were changed to somehow handle zero exchange rate,     // the body of the theory method would pass, but the     // assumption would still not be met and overall we will register a failure.     [InlineData("ExchangeRate Assumption Check", new object[] { 2.0, 1.0, 0.0 })]     // This case will fail, there is an assumption that the dollar value is not three,     // but passing in a value of 3 doesn't cause a failure in the code, demonstrating     // that the assumption serves no purpose     [InlineData("This should fail, assumption met but no failure in method", new object[] { 3.0, 1.0, 3.0 })]     [Assumption("ConvertToEurosAndBackExchangeRateIsNotZero")]     [Assumption("DollarsNotThree")]     public void MyTheoryCanConvertToFromEuros(double amountDollars, double amountEuros, double exchangeRateDollarsPerEuro)     {         // Should check are equivalent within a tolerance         // Calls static method on Convert method         Assert.AreEqual(amountDollars, Converter.ConvertEurosToDollars(Converter.ConvertDollarsToEuros(amountDollars,         exchangeRateDollarsPerEuro), exchangeRateDollarsPerEuro));     }     // Assumption is that the exchange rate is not zero     public bool ConvertToEurosAndBackExchangeRateIsNotZero(double amountDollars, double amountEuros, double exchangeRateDollarsPerEuro)     {         // Should have a tolerance on this         return exchangeRateDollarsPerEuro != 0.0;     }     // Assume that dollar value not equal to three     // This is just to demonstrate that an invalid assumption results in a failure.     public bool DollarsNotThree(double amountDollars, double amountEuros, double exchangeRateDollarsPerEuro)     {         return amountDollars != 3.0;     }     /// Returns the data for MyTestMethod     ///     public IList MyTestMethodData     {         get         {             List details = new List();             details.Add(new TheoryExampleDataDetail("Some other case should pass", new object[] { 2.0, 20.0, 5.0}));             return details;         }     } } public static class Converter {     public static double ConvertEurosToDollars(double amountDollars,         double dollarsPerEuro)     {         return amountDollars * dollarsPerEuro;     }     public static double ConvertDollarsToEuros(double amountEuros,         double dollarsPerEuro)     {         return amountEuros / dollarsPerEuro;     } }

A nicer syntax/api would be to have the assumptions inline:

public void CanConvertToEurosAndBack(double amountDollars, double amountEuros, double exchangeRateDollarsPerEuro){Assume.That(exchangeRateDollarsPerEuro != 0.0);Assume.That(amountDollars != 0.0);// Checks are equivalent within a tolerance// Calls static method on Convert methodAssert.AreEqual(amountDollars, Converter.ConvertEurosToDollars(Converter.ConvertDollarsToEuros(amountDollars,exchangeRateDollarsPerEuro),exchangeRateDollarsPerEuro));}

Here’s the rules of my Theory Implementation

If there is no example data, the theory passes (we may want to change this in the future).
If there are no assumptions for a theory, then each set of example data is executed against the theory each producing its own pass or fail.

If assumptions exist, the each set of data is first validated against the assumption – if it meets the assumption, then the test proceeds and any test failure is flagged as an error.
If the example data does not meet the assumption, then if the test passes it indicates that the assumption is invalid, and that case is marked as a failure, with a specific message “AssumptionFailed”. Any assertion failures or exceptions in the actual theory code are treated as passes. (in the future, would we want to mark the specific exception expected in the test methdo if an assumption is not met?).

NOTE: we may want to mark as a failure any theory for which ALL example data fails the assumptions, as a check that the
actual body of the theory is actually being executed. I’ve not done this for now as it would be trickier with the current
NUnit implementation.

Similarly, I was thinking of failing if any of the assumptions weren’t actually executed, but again, this is tricky in the current NUnit implementation (and may not give us much).

Automated exploration would not follow the last two suggested rules. The automation API would need to generate its data and execute it as if it were inline data. It may be helpful for the automated tool to be able to retrieve the user-supplied example data, so it doesn’t report a failure for any known case, but this is probably not necessary.

Feedback on these rules would be most welcome. If you want to change the behaviour of the assumptions (i.e. have assumptions only filter and nothing more), then the behaviour can be changed in TheoryMethod.RunTestMethod()

Here’s the output of the above theory:

## Theories

I’ve just released a slightly updated version of my NUnit extension for data-driven unit testing.

There’s been a lot of discussion on the NUnit developer list recently regarding Theories – something new in JUnit and xUnit.Net, and it’s taken a while to discover why they’re so powerful (they’re superficially very similar to data-driven unit tests, and a lot of the differences are semantics).

First, there’s some good background on theories written by David Saff:
http://shareandenjoy.saff.net/tdd-specifications.pdf
http://shareandenjoy.saff.net/2007/04/popper-and-junitfactory.html
http://dspace.mit.edu/bitstream/1721.1/40090/1/MIT-CSAIL-TR-2008-002.pdf

Theories on first glance look like a data-driven unit test, but I think that the most important difference is, is that:

Theories are, in theory (excuse the pun), supposed to pass for ANY POSSIBLE parameters, whereas data-driven tests only express the behaviour examples that the developer has provided (they are nothing new in unit testing – just a way for a developer to more clearly group parameters together, or get the parameterized data from an external data source without recompiling tests).

Theories are a generalized statement of how the program should run, whereas in TDDing, a very explicit statement of intent is made, which can be made to pass by coding that specific case in the implementation, and then the program is made to work by triangulization – expressing the generalization by giving more inputs. However, the theory literature points out that as we haven’t passed in too many data points we can’t be sure whether we’ve actually expressed what we meant.

Theories, by forcing us to write our tests such that they take any inputs, are much more powerful a statement, and allow for the possible inputs to be explored with external tools.

As an aside, one question I posted to the NUnit developer list regarding theories: “One thing that comes to mind, is that theories are written such that all possible inputs should pass. Apart from using a tool such as agitator, is there a way to test that the tests are written in a general way (I mean, if you had a theory that took parameters, but it totally ignored those parameters and worked as a vanilla unit test – i.e. created its own input), then it’s not really a valid theory – is
there a way to detect these cases? Probably not, but I was just idly wondering.” Answers on a postcard to… well, I’d prefer a reply comment 😉

This is a blog post to explain exactly what exactly parameterized data-driven unit testing is and why it’s there, and then to explain a bit about how this effected the implementation of the Rakija NUnit add-in.

First, what is data-driven unit testing? It’s running tests with data which is driven from external data (as may be from an xml file or database). NUnit makes this quite difficult, as the tests are attribute driven, they are fixed, and fixed at the time that the tests are created.

Data-driven fixtures.
A common desire is to run fixtures with different set of parameters. An example of this is to test key input filtering under different UI cultures.

This is a very contrived example, and the tests are in no way realistic, but it demonstrates what data-driven tests are about. My example is a simple class that takes various string inputs and performs operations on them. Here it is:

///

/// Parses and operates on various string values.
///

public static class ValueParser
{
///

/// Returns the addition of two strings representing
/// double values.
///

/// The combined value.
(string value1, string value2)
{
return double.Parse(value1) + double.Parse(value2);
}
}

And of course, the contributing unit test:

[TestFixture]
public class TestValueParser
{
[Test]
{
“2.3”, “2.2”));
}
}

Of course in real life, we’d have tests to pass in garbage input, checking for any exceptions etc. Our class would also be much larger, containing many methods, along with many (maybe hundreds) of corresponding unit tests in our test fixture. We’ve happily deployed the first release of our software, and have many happy customers, when our customer representative or product manager informs us that we need our software to run on European users computers. We don’t get panicked, we know that our input data is coming from XML, and is formatted in invariant culture, but we need to make sure to change our code such that double.Parse takes in CultureInfo.InvariantCulture. We’d ideally like to ensure that our tests run in both cultures. We could duplicate our fixture with a different setup test, but we all know that duplicate code is bad, right? So we use the following pattern.

// NOTE: TestFixture class has been removed.
public class TestValueParser
{
protected string cultureString = “invalid”;
private CultureInfo initialCulture;

[SetUp]
public void Setup()
{
this.initialCulture
CultureInfo.GetCultureInfoByIetfLanguageTag(
cultureString);
}

[TearDown]
public void TearDown()
{
this.initialCulture;
}

[Test]
{
“2.3”, “2.2”));
}
}

[TestFixture]
public class TestValueParserUSCulture : TestValueParser
{
public TestValueParserUSCulture()
{
cultureString = “en-US”;
}
}

[TestFixture]
public class TestValueParserFRCulture : TestValueParser
{
public TestValueParserFRCulture()
{
cultureString = “fr-FR”;
}
}

We leave all of our tests intact, we have to make some minor modifications to our original test fixture (remove the test fixture attribute, and do some setup work), but we’re able to test our fix very quickly (obviously we follow red bar/green bar/refactor, and write the tests before changing our code), and as we have a high test code the new release of the software works flawlessly, we finish early and spend the remaining time playing Crysis.

This pattern is very common in NUnit, but I haven’t found it named anywhere, I call it the Test Fixture Inheritance Pattern. NOTE: This pattern is not supported in Visual Studio Team System 2005 testing, but it’s fixed in the 2008 version.

(As an aside, I’ve read about the upcoming xUnit framework, and it says that tests aren’t grouped into fixtures, I’m not sure how it would cope with this pattern in that case? It’s possible that you could parameterized each test, and use something like a RowTest attribute to pass in the culture string, but by testing a new culture you’d have to add a new attribute to each and every test.)

The first thing to notice about the Test Fixture Inheritance Pattern is that it isn’t very OO. It wouldn’t be too much work though to create an NUnit extension that would allow parameterizing the test fixture constructor, in a similar way to how the RowTest attribute works, i.e.

[TestFixture]
[Parameter(“en-US”)]
[Parameter(“fr-FR”)]
public class TestValueParser
{
protected string cultureString = “invalid”;
private CultureInfo initialCulture;

public TestValueParser(string cultureString)
{
this.cultureString = cultureString;
}

[SetUp]
public void Setup()
{
this.initialCulture
CultureInfo.GetCultureInfoByIetfLanguageTag(
cultureString);
}

[TearDown]
public void TearDown()
{
this.initialCulture;
}

[Test]
{
“2.3”, “2.2”));
}
}

That would be nothing more than syntactic sugar though (it does make the tests look much neater). This could be more powerful though – it could be expanded to read data from a database or an XML file (again, similar to VSTS’s DataSource attribute).

Rakija instead provides an interface IDynamicFixtureSpecifier, which is used on a class to specify which fixtures to create. Each fixture then must implement another interface, and the fixture need to implement IDynamicFixture. Our example now looks like this:

// NOTE: TestFixture attribute has been removed.
public class TestValueParser : IDynamicFixture
{
protected string cultureString = “invalid”;
private CultureInfo initialCulture;

public TestValueParser(string cultureString)
{
this.cultureString = cultureString;
}

[SetUp]
public void Setup()
{
this.initialCulture
CultureInfo.GetCultureInfoByIetfLanguageTag(
cultureString);
}

[TearDown]
public void TearDown()
{
this.initialCulture;
}

[Test]
{
“2.3”, “2.2”));
}

#region IDynamicFixture Members

public string Name
{
get { return “TestValueParser ” + cultureString; }
}

#endregion
}

The fact that this is a test fixture is detected from the add-in by the fact that it implements IDynamicFixture, I could have instead created a new attribute for the class, and either reflected for the Name property (or created an attribute to return the name), but that’s by-the-by.

To actually specify the instances of our fixture, we use code like the following:

public class SpecifyFixtures : IDynamicFixtureSpecifier
{
#region IDynamicFixtureSpecifier Members

public Type FixtureType
{
get
{
return typeof(TestValueParser);
}
}

public IList GetUserFixtures()
{
List fixtures =
new List(2);
return fixtures;
}

#endregion
}

Your first thought may be to wonder why I’ve created such a convoluted way of creating fixtures, when a page or so ago I showed how neatly this could be done by creating a new attribute. Well, this is much more powerful, we’re not limited to querying a database or reading an XML file – we could load up our assembly to test, and reflect over certain types in it, creating a new fixture for each type. The sky’s the limit.

Parameterized test methods.
I’ll quickly go over the motivation over parameterized test methods, before discussing why I’ve been forced to implement these myself due to the current NUnit (as of 2.4.6) extension interface, rather than deferring these to Kelly Anderson’s extension.

Another common requirement when unit testing is to run a given test with different input data. Before the existence of any RowTest attribute, a common thing to do may have been.

[Test]
public void SomeTest()
{
// .. read some data in an xml file
// .. for each piece of data, perform some common testing
// .. { assert on the data; }
}

This obviously works, but the problem of it is lack of visibility/feedback. For a file that may contain hundreds of pieces of data, we have a single red or green bar. We’d like to have visibility of each individual case. VSTS has a DataSource attribute to cope with this cases like this (reading from a database or XML File).

Now that I’ve, very briefly, covered the motivations behind parameterized test cases, I’m going to go into the implementation details of Rakija.

Kelly Anderson has created a more powerful interface, similar to Rakija’s, where a method can be decorated with an IterativeTest attribute to specify the test data for the test. (Kelly’s interface is much more user-friendly than Rakija’s).

Unfortunately, I’ve had to duplicate the functionality of this Kelly’s work in Rakija, due to the internals of NUnit’s extensibility mechanism. I’ll explain why below, and propose a change to the mechanism to allow the extensions to co-exist.

Similar to Rakija, Kelly’s mechanism creates a TestCaseBuilder to recognise the parameterized test cases. This works without any problem, but will fail when used with any of the above parameterized test fixtures described above.

Kelly’s extension works by finding the method decorated with his IterativeTestAttribute, creating a new instance of the type that contains that attribute, and calling the method decorated by that attribute to find the parameters to create the test with. He gets away with creating a new instance of the type by the fact that all instances of the type will contain the same data.

The problem comes when you have parameterized test cases – each test case has been created with different parameters, and depending on those constructor parameters we may wish to pass different parameters to our tests (our test fixtures may have been created with a given node of an xml file, and we may wish to pass various sub-nodes of that node to an XML file).

Rakija is forced to deal with this situation by taking control of the parameterized test case situation when parameterized fixtures are also involved.

The proposed fix, to allow dynamic fixtures to exist with any other extension (e.g. Kelly Anderson’s IterativeTest extension, or Andreas Schlapsi’s RowTest extension) is to make a change to the extensibility mechanism.

Currently, NUnitTestFixtureBuilder (or our derived class), has to call

this.testCaseBuilders.BuildFrom(method);

where method is a MethodInfo
And this forces each test case builder either call a static method, or construct a type to create a method on. The return type from this method is a test, which gets added onto the fixture/suite’s list of tests to run.

In the parameterized fixture case, the interface on AbstractTestCaseBuilder would better be:
protected override TestCase MakeTestCase(object instance, MethodInfo method);

or something similar, where instance would be the instance that contains the method. That would allow the method to be invoked on the instance that it lived on, allowing parameterized fixtures to co-exist with the other mentioned extensions.