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: , ,

2 Comments:

Anonymous Anonymous said...

Hi,

but doesn't that lead to duplicate code?
At least in some circumstances?

Mon Mar 23, 08:51:00 AM 2009  
Blogger Kevin Rogiers said...

Hello,

Isn't there a mismatch in your comparison?
For the method with three arguments you assume to test 3 operations. Leading to 27 tests. But you when replacing the three-argument method by two-argument methods, you only make a method for 2 of the three operations. As a result, you only need 18 tests in this new scenario. If you had created three new methods, one for each of the three operations, you'll also end up with 27 tests, and thus there won't be any improvement.

Thu Sep 03, 10:38:00 AM 2009  

Post a Comment

<< Home