Re.Mark

My Life As A Blog

Archive for the ‘Unit Testing’ Category

Limits to Independence

leave a comment »

The solution I described yesterday has a drawback – it increases the scope of the created class. This may be acceptable – it may even be desirable – in some instances, but there are situations where you have to think of something else. In the case of nspectre, a reference ValidatorFactory needs to held for the lifetime of an application because it compiles the specifications once when they are first required. So, if we were to hold references at class level in ValidatorFactory, they would never be eligible for garbage collection.
Let's say we have a class called, uninspiringly, Foo that creates an instance of class called – you guessed correctly – Bar. One solution is to create a protected method in Foo that returns a new instance of Bar. In our unit tests we subclass Foo and override the newly created protected method. Then we can either extract the interface from Bar and make Bar implement this interface (IBar) and mock Bar in the unit tests. It would also be possible to return a fake Bar – maybe by subclassing Bar.

Written by remark

April 26, 2006 at 8:05 pm

More Independence

leave a comment »

Having put in a few logging messages into nspectre to prove the principle, it's time to test the logging messages. Given that the design relies on an ILogger interface, this is fairly easy with mocks. What I noticed fairly quickly was a class that created another class – which meant that testing logging would mean testing it in more than the target class.
The solution is to extract an interface from the class being created by the target class and pass it to the target class in the constructor. Now I can also mock the class that was being created. In this instance, the code that results is more elegant. All tests have been updated and they all pass. Once more the tests have proven their worth – this kind of refactoring would have been scary without them.

Written by remark

April 25, 2006 at 10:57 pm