Couple Inputs to Outputs

How many times have you seen tests that resemble the following?

assertEquals(4, transformIt(2));

What are the meanings of the literal values 2 and 4 in this code? Sure, you can read the documentation, assuming it exists, for transformIt() and know what it is supposed to do. In the absence of documentation, you can look at the implementation and reverse engineer the code, but then you are testing implementation, not intent. Also, the author of code such as this requires each following developer to decipher his own intent in addition to whatever intent needs to be extracted from the code under test.

Would you rather see something like Listing 5-1 instead?

Listing 5-1: Coupling inputs to outputs in tests

int operand = 2;
int expectedSquare = operand * operand;

int actual = transformIt(operand);

assertEquals(expectedSquare, actual);

Although the example is a bit simplistic and contrived, the code reads in a much more intent-revealing way. Perhaps more importantly, the code clearly communicates the intended testing relationship between the input operand and the output expectedSquare to all future maintainers. If transformIt() changes, the test’s prior expectation will be clear to all involved.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.144.97.216