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);
// Properties
public 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.Labels: TDD, Theories, Unit testing