Consider the problem writing a unit test for the IList.Add method. At first sight this is trivial (as an example, we check that IList.Add supports null reference):
IList.Add
null
[TypeFixture(typeof(IList))] public class ListTest { [Test("List accepts null values")] public void AddNull(IList list) { list.Add(null); ... } }
Now what about the Readonly and the FixedSize wrapper of ArrayList. They implement IList, but calling IList.Add on them will throw a NotSupportedException. Using the classic ExpectedExceptionAttribute technique, the only solution is to create a special fixture for read-only and fixed size wrappers, and that involves a lot of code duplication.
IList
NotSupportedException
ExpectedExceptionAttribute
To tackle this problem, I have added ConditionalExceptionAttribute, which expects an exception if a predicate is true. The predicate is define by a method of the fixture that returns a boolean. This solution is simple and avoids the duplicate of unit tests when possible. Let's addapt the example with the new decorator:
[TypeFixture(typeof(IList))] public class ListTest { public bool IsReadOnly(IList list) { return list.ReadOnly; } [Test("List accepts null values")] [ConditionalException(typeof(NotSupportedException),"IsReadOnly")] public void AddNull(IList list) { list.Add(null); ... } }
When the test will be executed, if list.ReadOnly is true, the framework will expect to receive a NotSupportedException, but if it is false, he will not check for exception. Note that the parameters of the predicate must match the parameters of the test method and it must return a bool.
list.ReadOnly
bool
Page rendered at Thursday, December 04, 2008 8:04:43 AM UTC
Disclaimer The opinions expressed herein are my own personal opinions and do not represent my employer's view in anyway.