Sunday, September 09, 2007

Lose Those Extra Parameters

Most unit testing strategies focus on a method's parameters. By definition, they control the behavior of the method under test, so varying the input values of the method, one can build a strong test suite. But the more parameters that your method under test has, the more tests that will be required to do complete black-box testing. Obviously, most methods take one or more parameters, but if there are clear ways to limit the number of parameters, it will be a clear win for black-box testing scenarios.

Consider this method signature:

public int addOrSubtract(int x, int y, Operator operator)

Each additional parameter increases the number of possible combinations that you'd likely want to test. If you try three possible values for each parameter, that's 27 tests for this method. If there are only two possible operators (addition and subtraction), we could refactor this method into two simpler ones:

public int add(int x, int y)
public int subtract(int x, int y)


Now, even if we try three possible values for each parameter, we still only wind up with nine combinations for each method, or 18 total -- we've reduced our testing effort by one-third. Obviously, there is no cut-and-dried method for reducing the number of parameters, and there may indeed be cases where your method under test does require many parameters, but by keeping the method's signature to as few parameters as possible, you'll save yourself testing effort down the road.

Labels: , ,