Testing Building Code

Or, "How to Test Code That Calls a Builder?"


I'll have to improve the description below. I don't have much time right now... --MarnixKlooster


You've written code that calls a Builder (as in the BuilderPattern; see DesignPatterns from the GangOfFour). How do you test it?

Here's what I currently do. Have a BuilderForTest?, which implements the same interface as the original Builder, and which can be in two modes: recording and verifying. Initially it is in recording mode. In your test code, you send it all buildXYZ() messages that you expect to be called later by the Builder-calling code. It records all these messages internally. Then you say "builderForTest.beginVerification()", and you start the code-to-be-tested. That code will call buildXYZ() methods, which will now compare these calls with the calls recorded in recording mode. When everything is OK, the builderForTest does nothing. But when something goes wrong, it complains. (In JUnit, probably by calling an assert() method on a TestCase that you passed into the BuilderForTest?.) If all went OK, you call a "builderForTest.endVerification()", which checks whether there are any calls 'left over' in recording mode.

The big advantage (in my experience) is that this pinpoints errors during execution of the building code: if you stop at the point where the verification fails, you are probably close to the point where the error is in your code. That helped me a lot lately.

This can be implemented using the State pattern: the BuilderForTest? internally maintains a BuildLog?, of which there are two versions: a RecordingBuildLog? (which stores calls, probably as a sequence of Strings), and a VerifyingBuildLog? (which holds a reference to a RecordingBuildLog?, and an index into the record).


EditText of this page (last edited January 31, 2000) or FindPage with title or text search