Verify a validation method is called that doesn’t throw exceptions

The strategy laid out in Testing strategy for validation and action methods calls for a single test per action method, to show that it actually calls the validation method.

Validation methods throwing exceptions on invalid input provide you with a handy means of checking whether it has been called by your action methods. All you need to do is supply your action methods with invalid input and wait for the exception to go off.

But what if your validation method doesn’t throw exceptions? Then there is no exception to wait for! What do you do then?

Well, you hope…

Nah, of course not.

There are two options, really. Your validation method has some other side effect besides throwing a tantrum or two, or it doesn’t. The former we’ll discuss now, the latter will have to wait for another time.

Simply put, if your validation method doesn’t throw exceptions but does have other side effects that you can check for, you are home free. All you then have to do is write a test that feeds valid or invalid input to your action method and then verify that the expected side effect did occur.

Code example

So, instead of a validation method that throws exceptions, you have a validation method that has other side effect. For example it adds an error message to an internal list.

    private List<string> _Errors = new List<string>();
    public void ValidateInput(string key, int index)
    {
        if (string.IsNullOrEmpty(key)) 
          _Errors.Add("Key should not be an empty string.");
        // ... snip ...
    }

Good, now you have something to work with. Unfortunately, the list of error messages is private so you can’t get at it from your tests.

Or can you?

Having a list of error messages somewhere without any means of getting its contents is futile to say the least. It is pretty safe to expect that this class provides some way to find out why the action method that was called didn’t have the desired result. Either a method to get the text of all the error messages or at the very least some Boolean LastValidationResult property.

Let’s go with the error text.

    private List<string> _Errors = new List<string>();
    public string ErrorText { get { return string.Concat(_Errors); } }

    // ... snip ...
    public void ValidateInputAddingMessage(string key, int index)
    {
        _Errors.Clear();
        if (index < 0) 
            _Errors.Add("Index can not have a negative value.");
        if (index > _List.Count) 
            _Errors.Add(String.Format("Cannot add at index {0}. The list is only {1} items long.", index, _List.Count));
        if (string.IsNullOrEmpty(key)) 
            _Errors.Add("Cannot add an empty string.");
        if (_List.Contains(key)) 
            _Errors.Add(String.Format("Cannot add {0}. It is already present at index {1}.", key, _List.IndexOf(key)));

The test to check that for example the AddKey action method indeed does call the ValidateInput method would then be a very simple check on the value of the ErrorText property..

    [TestMethod]
    public void ValidateInput_EmptyString_ShouldCause_NonEmptyErrorText()
    {
        var list = MakeAugmentedList();
 
        list.ValidateInput("", 0);

        Assert.AreNotEqual(list.ErrorText, "");
    }

That’s it. Enjoy!

What code had you wondering how to test it? I’d love hearing from you by email or in the comments below. I read everything and will try to help where and as best I can.

Posted in Software Development
Tags: , , , , , ,

Act like a pessimist and call CanHandle from Handle (again)?

You have multiple Worker classes that can each handle a one or more types of command. Your IWorker interface offers two methods: CanHandle and Handle.

    interface IWorker
    {
        public Boolean CanHandle(IWork work);
        public void Handle(IWork work);
    }

Perfect.

Anyone with work to be done can now find a worker that says “yay, I can handle this” and then pass off the work to that worker.

What if someone doesn’t call CanHandle first?

But what if someone offering work just throws work at the Handle method of any Worker they happen to know?

You could face all manner of exceptions when someone sends KitchenWork to a BathroomWorker. The BathroomWorker stands no chance treating KitchenWork as BathroomWork. Exceptions could be flying high and low, or worse, you could end up with a very clean instead of a cooked chicken.

Just try to figure that one out when you receive the bug report as you are about to go home…

Act like a pessimist and call CanHandle from Handle (again)?

The simplest solution is to call CanHandle from Handle and throw a very specific exception when that returns false.

    class BaseWorker : IWorker
    {
        public Boolean CanHandle(IWork work) { return false; }
        public void Handle(IWork work) 
        {
            if (!CanHandle(work))
                throw new CanHandleNotCheckedError("You should call CanHandle before calling Handle");

            // ... snip ...
        }
    }

The advantages are obvious. When someone blatantly ignores the CanHandleHandle pattern, you now get a very specific exception of the root cause and program execution wouldn’t even get into the territory where other exceptions would be caused.

And punish the good guys with double execution?

The disadvantage is that every polite client of your Workers is punished with double execution of the CanHandle method.

That’s not very nice.

And it can add up, especially if CanHandle is a bit more involved than just a type check or two.

So, should you act like a pessimist and call CanHandle from Handle again?

If you like to go home earlyish: Yes, but…

Do you like to go home earlyish?

Or do you like being the “hero” and spending hours on some hard to debug errors?

If you are like me and like to go home on time, then yes, you do want to call CanHandle from Handle again.

When you can’t enforce that everybody behaves as good guys, it’s the only way to guarantee that the actual “handling” code is protected from being given something it can’t handle.

… you don’t need to punish the good guys

You can still be nice to the good guys too.

The contract for Handle is violated when someone doesn’t call CanHandle first. Looking at it like that tells you that you could put the “extra” CanHandle call in an Assert statement.

In C# assert statements come in two flavors.

    Debug.Assert(CanHandle(work), "You should call CanHandle before calling Handle");

and

    Trace.Assert(CanHandle(work), "You should call CanHandle before calling Handle");

The difference is that Debug.Assert automatically gets thrown out for Release builds, while Trace.Assert stays in. So in this particular case you want to use the Debug.Assert version.

Using a Debug.Assert, the bad guys get slapped with an assertion failure when doing it wrong, while the good guys don’t incur the overhead in release builds.

Sounds like the best of both worlds…

That’s it. Enjoy!

Can you think of another alternative? Let me know in the comments below or by email.
My own alternative will be out in a couple of posts.

Posted in Software Development
Tags: , , , ,

Testing strategy for validation and action methods

How do you test a set of methods that call each other without repeating yourself unnecessarily?

You are more than tired of debugging “List index out of bounds”, “Duplicates not allowed” and similar exceptions. You want some help from your code so you don’t have to hit “Next” until you are blue in the face to figure out the information not contained in the standard exception messages.

So you created a class that checks the input parameters before actually performing any manipulations on a list. Staying true to the DRY principle, you created a method that does the checking and that is called by all manipulation methods.

    class AugmentedList
    {
        private List<string> _List = new List<string>();
        public int Count { get { return _List.Count; } }

        public void ValidateInput(string key, int index)
        {
            // Input validation code
        }

        public void AddKey(string key)
        {
            AddKey(key, _List.Count);
        }

        public void AddKey(string key, int index)
        {
            ValidateInput(key, index);
            // ... snip ...
        }

        public void MoveKey(string key, int fromIndex, int toIndex)
        {
            ValidateInput(key, fromIndex);
            ValidateInput(key, toIndex);
            // ... snip ...
        }

        public void RemoveKey(string key, int index)
        {
            ValidateInput(key, index);
            // ... snip ...
        }
    }

Now you face a conundrum.

Should you repeat the tests for each caller?

When you wrote the ValidateInput method you also wrote a fair number of tests to ensure it does what it should and won’t be tripped up inadvertently by future changes to the code.

Should you now repeat all those tests for each method that calls the ValidateInput method?

After all, the tests for the manipulation methods aren’t complete if you don’t test that they check their input arguments? But repeating the ValidateInput methods tests for a manipulation method sounds like a gross violation of duplication/copy-paste principles. Especially when you would do that for every manipulation method!

Repeating the tests means that they need to be kept in sync. And you really do not want to do that because it poses a maintenance burden you can do without.

Relax. There is no need to violate any principles.

How not to repeat tests

The testing strategy for such a validation method / action method combination is straightforward. All you have to do is:

  1. Test the heck out of the validation method.
  2. Do not duplicate these tests for the action methods.
  3. Do write a single test for each action method to show that it actually calls the validation method.
  4. Do write tests for each action method to check its behavior given invalid input.
  5. Test the heck out of each action method to check its behavior given valid input.

Code example

Start by creating a test class with a factory method to instantiate your class under test: the AugmentedList class.

    [TestClass]
    public class AugmentedList_Tests
    {
        private AugmentedList MakeAugmentedList()
        {
            return new AugmentedList();
        }

    }

Test the heck out of the validation method

Add the tests you need to ensure that ValidateInput does what it needs to do and keeps doing it regardless of future changes to your code.

        [TestMethod]
        [ExpectedException(typeof(AugmentedListEmptyStringError))]
        public void ValidateInput_EmptyString_ShouldThrow_AugmentedListEmptyStringError()
        {
            var list = MakeAugmentedList();

            list.ValidateInput("", 0);
        }

        [TestMethod]
        [ExpectedException(typeof(AugmentedListDuplicateStringError))]
        public void ValidateInput_DuplicateString_ShouldThrow_AugmentedListDuplicateStringError()
        {
            var list = MakeAugmentedList();
            list.AddKey("Duplicate");

            list.ValidateInput("Duplicate", 0);
        }

        [TestMethod]
        [ExpectedException(typeof(AugmentedListNegativeIndexError))]
        public void ValidateInput_IndexNegative_ShouldThrow_AugmentedListNegativeIndexError()
        {
            var list = MakeAugmentedList();

            list.ValidateInput("SomeKey", -1);
        }

        [TestMethod]
        public void ValidateInput_IndexEqualToCount_ShouldNotThrow_AnyError()
        {
            var list = MakeAugmentedList();

            list.ValidateInput("SomeKey", 0);

            // Assert.DoesNotThrow
        }

        [TestMethod]
        [ExpectedException(typeof(AugmentedListIndexTooHighError))]
        public void ValidateInput_IndexHigherThanCount_ShouldThrow_AugmentedListIndexTooHighError()
        {
            var list = MakeAugmentedList();

            list.ValidateInput("SomeKey", 1);
        }

With this bunch of tests you ensure that ValidateInput throws specific exception types instead of just plain Exceptions. You could add additional tests to check that the exceptions thrown actually contain the specific information the AugmentedList class should have passed to the exception constructor. Thus ensuring that you actually do get the extra information you wanted.

The ValidateInput_IndexEqualToCount_ShouldNotThrow_AnyError of course does not have an ExpectedException attribute. It does not have an Assert either. The test is intended to assure that no error is thrown for the given input arguments. Given that ValidateInput does not have a return type, there isn’t much to assert on. Other test unit frameworks have an Assert.DoesNotThrow method to cover this scenario. Unfortunately MSTest (the Microsoft Unit Testing Framework) does not have such a method. Adding a comment to the same effect is often a very useful way to make your intentions explicit.

Write a single test for each action method to show that it actually calls the validation method

Given that ValidateInput throws exceptions on invalid input, it is pretty easy to ensure that each action method calls the validation method. You simply add a test for the action method, feed it invalid input and expect the exception.

        [TestMethod]
        [ExpectedException(typeof(AugmentedListNegativeIndexError))]
        public void AddKey_ShouldCall_ValidateInput()
        {
            var list = MakeAugmentedList();
            list.AddKey("Irrelevant", -1);
        }

If AddKey does not call (or no longer calls) ValidateInput, bets are on that this test starts failing because no exception is thrown.

Of course some clever prankster could thwart this check by checking for this input in X and returning the same exception. But you have to draw the line somewhere. You are not protecting against hackers but against someone forgetting to use ValidateInput and/or inadvertent removal of the call to ValidateInput.

Write tests for each action method to check its behavior given invalid input

All your action methods should still behave correctly when faced with invalid input. They should at the very least catch the exceptions thrown by ValidateInput and proceed accordingly.

For example when AddKey is given invalid input, it should not only use ValidateInput to discover it, but it should also not add any invalid input to your list. So you would want a test to check that given invalid input, AddKey leaves the contents of the list as they were.

Similarly, as the AugmentedList does not allow duplicates, you should have a test that shows that AddKey does not change the contents of the list when it is passed a duplicate value.

        [TestMethod]
        public void AddKey_InvalidInput_ShouldNotChange_ContentsOfList()
        {
            var list = MakeAugmentedList();
            var listCopy = MakeAugmentedList();

            try
            {
                list.AddKey("", 0);
            }
            catch
            {
                // Ignore for the purpose of this test
            }

            Assert.AreEqual(string.Concat(listCopy), string.Concat(list));
        }

        [TestMethod]
        public void AddKey_StringAlreadyPresent_ShouldNotChange_NumberOfItems()
        {
            var list = MakeAugmentedList();
            var listCopy = MakeAugmentedList();
            list.AddKey("Duplicate");
            listCopy.AddKey("Duplicate");

            try
            {
                list.AddKey("Duplicate", 0);
            }
            catch
            {
                // Ignore for the purpose of this test
            }

            Assert.AreEqual(listCopy.Count, list.Count);
        }

If you get the impression that you are repeating the input values that you fed ValidateInput to test AddKey, then you are … very much right.

Depending on the implementation of the validation method, the test to show that an action method actually calls the validation method can indeed have much the same implementation as the test to check an action method’s behavior on invalid input.

You still code them BOTH!

Even though it looks like un-dry, soggy code, it isn’t and in this case you do want to “repeat” yourself. [1] The intention of the tests is very different, which – if you do it right – is reflected in the names of the tests. The fact that these tests may have (almost) the same implementation is less important if not totally irrelevant. What is important is that each test documents and assures a different aspect of your class’ behavior and thus represents a different piece of knowledge about your class.

Test the heck out of each action method to check its behavior given valid input

With the tests in place that assure that ValidateInput is called and that assure the correct behavior of your action methods when you pass them invalid input, you can now focus on testing the behavior of your action methods for valid inputs.

        [TestMethod]
        public void AddKey_StringNotYetPresent_ShouldIncrease_NumberOfItems() { }
        [TestMethod]
        public void AddKey_StringNotYetPresent_ShouldReturn_StringAtGivenIndex() { }
        [TestMethod]
        public void AddKey_NoIndexParam_StringNotYetPresent_ShouldIncrease_NumberOfItems() { }
        [TestMethod]
        public void AddKey_NoIndexParam_StringNotYetPresent_ShouldReturn_StringAtEndOfList() { }

That’s it. Enjoy!

What code had you wondering how to test it? I’d love hearing from you by email or in the comments below. I read everything and will try to help where and as best I can.

Notes

[1] The idea behind DRY is far grander than avoiding code duplication. It is more about avoiding knowledge duplication in your application’s sources and that is not just code, but includes database schemas, installation scripts etc. See Orthogonality and the DRY Principle for an interesting read.

Posted in Software Development
Tags: , , , , , , ,

Testing every implementer of an interface with the same tests using MSTest

You have an interface and multiple implementers of that interface. You want to test all those implementing classes using the same tests. And you do not want to repeat yourself. That would be … like … Gah!

Using NUnit that is a breeze. But you, you use MSTest, the Microsoft Unit Testing Framework.

So, just for fun, you try porting the example in NUnit post on testing implementers of an interface to the Microsoft Unit Testing Framework.

And run into all manner of problems. But fear not. There is a solution and it actually is pretty easy to boot.

The journey

1. Convert the attributes

For your first try using MSTest, you basically copy the code and rename the attributes. TestFixture becomes TestClass and Test becomes TestMethod.

As the TestClass attribute doesn’t support any arguments, you take them off, leaving you with a single, bare TestClass attribute. That’s a hint by the way that you have no easy way of telling MSTest for which classes to run these tests…

2. Mark the class and methods public

MSTest requires every class that contains test methods and every method to be run as a test to be public, or it won’t play ball and ignores them regardless of the attributes. So you dutifully add the public accessibility level to both the class and our single test method.

    class PieceOfWood_Fake : IPieceOfWood {}

    [TestClass]
    public class IJointer_Contract_MS<T> where T : IJointer, new()
    {
        IJointer MakeJointer()
        {
            return new T();
        }

        [TestMethod]
        [TestCategory("Jointer")]
        public void MakeDoveTailJoint_No_Exceptions_Raised_Should_Return_Non_Null_DoveTailJoint()
        {
            var jointer = MakeJointer();
            var DoveTailJoint = jointer.MakeDoveTailJoint(new PieceOfWood_Fake(), new PieceOfWood_Fake());
            Assert.IsNotNull(DoveTailJoint);
        }
    }

That comes back to bite you in the behind though with the compiler complaining:

Inconsistent accessibility: constraint type 'ActualProject.InterfaceContract.IJointer' is less accessible than 'TestProject.InterfaceContract.IJointer_Contract_MS'

Duizend bommen en granaten![1]

You really don’t want to make the code in your actual project any more accessible from the outside than absolutely strictly necessary. Catering to unit tests is never a good reason to increase the accessibility level and while IJointer may be an interface, it still is an internal implementation detail of the actual project and should remain so.

Introduce a public base interface?

Could you get around this by introducing a public “test” interface that IJointer can derive from? It does mean adding a superfluous interface to the actual project, but you’ll take that over increasing IJointer‘s accessibility level.

    public interface IAny {}

    interface IJointer : IAny
    {
        IDoveTailJoint MakeDoveTailJoint(IPieceOfWood woodTails, IPieceOfWood woodPins);
    }

And you can now declare the testclass using the public IAny, which keeps the compiler happy.

    [TestClass]
    public class IJointer_Contract_MS<T> where T : IAny, new()
    {
        IJointer MakeJointer()
        {
            return new T() as IJointer;
        }
    }

3. Tell MSTest for which classes to run the tests

Now that you have a generic test class that can be used to test all classes implementing the IJointer interface, you need a way to tell MSTest for which classes to do so. That would be both the FirstJointer and SecondJointer classes from the NUnit example.

Deriving a specific test class from the generic test class?

As the TestClass attribute does not support constructor arguments like NUnit’s TestFixture attribute, that’s out, so … what about deriving a specific class from the generic one?

    [TestClass]
    public class IJointer_FirstJointer : IJointer_Contract_MS<FirstJointer> { }

Looks good, but… Nope.

That runs into the exact same problem with regard to accessibility levels as you faced with the IJointer interface.

Inconsistent accessibility: base class 'TestProject.InterfaceContract.IJointer_Contract_MS' is less accessible than class 'TestProject.InterfaceContract.IJointer_FirstJointer'

Introduce a public base class?

You could create a public abstract AnyJointer class that every IJointer implementer could derive from.

    public abstract class AnyJointer : IJointer 
    {
        public abstract IDoveTailJoint MakeDoveTailJoint(IPieceOfWood woodTails, IPieceOfWood woodPins);
    }

    class FirstJointer : AnyJointer
    {
        public override IDoveTailJoint MakeDoveTailJoint(IPieceOfWood woodTails, IPieceOfWood woodPins)
        {
            return new FirstDoveTailJoint();
        }
    }

But, really, could derive from? Doing it like this means “could” becomes “should”. And that totally defeats (one of) the object(s) of using interfaces! You would no longer be free to make any class implement IJointer. Every class implementing IJointer would now have to fit into a very specific class hierarchy.

And it is not even going to work, because

    [TestClass]
    public class IJointer_FirstJointer : IJointer_Contract_MS<AnyJointer> { }

would make

    public class IJointer_Contract_MS<T> where T : IAny, new()
    {
        IJointer MakeJointer()
        {
            return new T() as IJointer;
        }
    }

instantiate the AnyJointer class, which, besides being impossible as it is abstract – easily overcome by not marking it such, is not what you need. You need instances of the FirstJointer and SecondJointer classes to test againt the IJointer interface contract.

Mark MakeJointer virtual?

To make the IJointer_FirstJointer test class return a FirstJointer instance you can make MakeJointer virtual in the contract class and override it.

    public class IJointer_Contract_MS<T> where T : IAny, new()
    {
        internal virtual IJointer MakeJointer()
        {
            return null;
        }
    }

And, better, mark it abstract so derived test classes are required to override it.

    public abstract class IJointer_Contract_MS<T> where T : IAny, new()
    {
        internal abstract IJointer MakeJointer();
    }

Notice that this requires you to mark the contract class abstract as well or you will get compiler errors.

But, but, but… that totally defeats the object of defining a generic test class!

Back to square one then?

In a sense, yes. And in this case, that is a good place to be.

If you ditch the generic test class, then you can also ditch everything you did to work around MSTest’s requirement that every test class and every test method should be public.

So you scrap IAny and AnyJointer in the actual project, which puts everything in there back to having an internal accessibility level only. Yay!

The solution

When you are using the Microsoft Unit Testing Framework and you want to leave everything in your actual project with no more than the internal accessibility level it should have, then to test every class implementing the IJointer interface with the same tests, you need to

  • use an abstract test class that defines the tests to be run, and
  • define specific test classes for each class implementing the interface.

1. Define an abstract base test class

    [TestClass]
    public abstract class IJointer_Contract_MS
    {
        internal abstract IJointer MakeJointer();

        [TestMethod]
        [TestCategory("Jointer")]
        public void MakeDoveTailJoint_No_Exceptions_Raised_Should_Return_Non_Null_DoveTailJoint()
        {
            var jointer = MakeJointer();
            var DoveTailJoint = jointer.MakeDoveTailJoint(new PieceOfWood_Fake(), new PieceOfWood_Fake());
            Assert.IsNotNull(DoveTailJoint);
        }
    }

2. Derive a specific test class per implementer

To make MSTest run the contract tests for each class implementing the IJointer interface, you have to derive a specific test class for each of them manually and provide each with its own implementation for the MakeJointer method.

    [TestClass]
    public class IJointer_FirstJointer : IJointer_Contract_MS 
    {
        internal override IJointer MakeJointer() { return new FirstJointer(); }
    }

    [TestClass]
    public class IJointer_SecondJointer : IJointer_Contract_MS
    {
        internal override IJointer MakeJointer() { return new SecondJointer(); }
    }

3. See the classes being tested against the same contract

MSTest_IJointer_First_And_SecondJointer

All in all a bit more work than using a generic test class and the TestFixture attribute as you can with NUnit, but not too bad at all.

That’s it. Enjoy!

What code had you wondering how to test it? I’d love hearing from you by email or in the comments below. I read everything and will try to help where and as best I can.

Notes

[1] Dutch version of a Captain Haddock expletive. Literal translation: “Thousand bombs and grenades!”. Closest English version is probably the “Ten thousand thundering typhoons!” one.

Posted in Software Development
Tags: , , , , , , , , , , ,

Testing every implementer of an interface with the same tests using NUnit

You have an interface and multiple implementers of that interface. You want to test all those implementing classes using the same tests. And you do not want to repeat yourself. That would be … like … Gah!

Using a unit test framework like NUnit that is a breeze.

You write the tests once. Using a reference to the interface in all of them. And then you tell your test runner to run these tests for every class that implements it. This way you test all these classes against the contract of the interface. Contract testing, pure and simple.

Let’s take another stab at dovetail joints:

    interface IJointer
    {
        IDoveTailJoint MakeDoveTailJoint(IPieceOfWood woodTails, IPieceOfWood woodPins);
    }

    interface IDoveTailJoint {}

    interface IPieceOfWood {}

Any implementer of the IJointer interface needs to honor the following contract for the MakeDoveTailJoint method:

  • Should throw ArgumentNullException when woodTails is unassigned
  • Should set ParamName of ArgumentNullException to woodTails when woodTails is unassigned
  • Should throw ArgumentNullException when woodPins is unassigned
  • Should set ParamName of ArgumentNullException to woodPins when woodPins is unassigned
  • Should return non-null reference to a DoveTailJoint when no exceptions are thrown
  • Should return DoveTailJoint with at least 1 tail
  • Should return DoveTailJoint with non-zero TailWidth
  • Should return DoveTailJoint with non-zero TailLength
  • Should return DoveTailJoint with non-zero FullPinWidth
  • Should return DoveTailJoint with non-zero SidePinWidth
  • Should return DoveTailJoint that fits woodTails’ width: ((number of tails) * TailWidth) + (((number of tails) – 1) * FullPinWidth) + (2 * SidePinWidth)

Once you know how to do it for one of these contract requirements, you can easily extend this to the others, so for brevity’s sake let’s focus on “Should return non-null reference to a DoveTailJoint when no exceptions are thrown”. The method to check this behavior would be something like:

    class PieceOfWood_Fake : IPieceOfWood {}

    public void MakeDoveTailJoint_No_Exceptions_Raised_Should_Return_Non_Null_DoveTailJoint()
    {
        var jointer = MakeJointer();
        var DoveTailJoint = jointer.MakeDoveTailJoint(new PieceOfWood_Fake(), 
            new PieceOfWood_Fake());
        Assert.IsNotNull(DoveTailJoint);
    }

So far so good. Now, you need to implement the MakeJointer method in such a way that when you run this method for the FirstJointer class, it returns an instance of FirstJointer and when you run it for the SecondJointer class, it returns an instance of SecondJointer.

Using NUnit, you can very simply do this by declaring a generic test class and constraining it so it can only be used for (types deriving from) IJointer:

    class IJointer_Contract<T> where T : IJointer, new()
    {
        IJointer MakeJointer() 
        {
            return new T();
        }

        public void MakeDoveTailJoint_No_Exceptions_Raised_Should_Return_Non_Null_DoveTailJoint()
        { // ... snip ... }
    }

The new() constraint on the class declaration enables you to create new instances of T. Without it, the compiler complains with the error message “Cannot create an instance of the variable type ‘T’ because it does not have the new() constraint” on the return new T(); line.

Now that you have a generic test class that can create a reference to IJointer, you still need to tell NUnit to run all the test methods in this class for every class implementing the IJointer interface.

With NUnit, that is as easy as adding an attribute to the test class:

    [TestFixture(typeof(FirstJointer))]
    [TestFixture(typeof(SecondJointer))]
    class IJointer_Contract<T> where T : IJointer, new()
    {
        // ... snip ...
    }

NUnit’s TestFixture attribute makes NUnit run the tests in the IJointer_Contract<T> test class with T substituted by the class specified in the attribute. In the above example, NUnit will run all the tests in IJointer_Contract<T> for both the FirstJointer and the SecondJointer classes.

IJointer_Tests_NUnit
Yeah, I know, the test fails… The Jointer classes still only satisfy the compiler by having return null; as their implementation for the MakeDoveTailJoint method. The other tests succeed only because the tests themselves are not yet implemented. See my moan about this in How to test a class hierarchy without repeating yourself.

That’s it. Enjoy!

What code had you wondering how to test it? I’d love hearing from you by email or in the comments below. I read everything and will try to help where and as best I can.

Posted in Software Development
Tags: , , , , , , , ,

Does your code defy you?

Sign up now and receive a regular influx of practical unit testing and software design tips to make your code more testable and improve its design. One small step at a time.
* = required field