Friday, April 11, 2014

Standard Output redirection in Java for a characterization test

Last weekend I did the UglyTrivia legacy code refactoring kata in Java.

Before starting to refactor, I added a characterization test to describe (characterize) the actual behavior of the original code. Since the only "visible effects" of the code were the lines it was writing to the standard output, I had to use that output to create the characterization test.

This is the code of the characterization test:

Although in this final version, the expected output reflects the fixing of two bugs in the original code, at the beginning it was just what the original code was writing to the standard output given a fixed seed for the random number generator.

This article describes this technique very well: Working Effectively With Characterization Tests.

To be able to redirect the standard output I used the StandardOutputRedirection class:

The characterization test shown before yielded a code coverage of 93% which gave me confidence enough to start refactoring the code.

No comments:

Post a Comment