Follow @RoyOsherove on Twitter

Code-Reuse in unit tests is more important than you think

Scott Bellware mentions how he really likes the new ideas in XUnit.NET, especially the lack of [Setup] and [TearDown] methods. (Brad Wilson wrote in the comments to my post about XUnit.NET that you can mimic this behavior by using the constructor of the test class and the IDisposable.Dispose() method of the class -just implement IDisposable) .

He especially says this:

"I think that Jim is on the right track, but I'm the kind of guy that feels that a test class's greatest responsibility is to document behavior in the clearest possible way, even if that means sacrificing design qualities best reserved for functional code - like reuse."

(emphasis mine)

That's silly. Scott tries to write "pure" TDD tests by saying that tests are 100% different than functional code, but they are not. Proof -- Tests that don't have code re-use in the form of setup and teardown or various specialized factory methods will be harder to maintain because every time you change some semantic aspect of your production code (constructors, initialization phases etc..) many of your tests will break and you'll have to fix them all one by one because you don't have re-use for object creation in your tests. Pretty soon you'll just stop maintaining your tests and that means you'll stop writing new ones. Ta-da! mission accomplished.

If we don't all realize that in the real world tests have to be as maintainable (or even more so) as production code, we won't come out of the middle ages of unit testing.

he then goes on to say some rules he has about Setup methods. one of which is:

"Don't put anything in a setup method that doesn't pertain to every test method in the test class"

I completely agree with this. You NEED to have re-use but you also need to make sure you don't abuse these abilities.

Do you like Boobs?

XUnit.NET aims to be the Next NUnit, but it's too soon