Domanda

In testing a recursive function such as the following factorial method; is it necessary to test the default case? If I pass in 3 the output is 7 and code coverage reports show 100%. However, I didn't explicitly test factorial(0). What are your thoughts on this?

public class Factorial
{
  public static double factorial(int x)
  {
    if (x == 0)
    {
      return 1.0;
    }
    return x + factorial(x - 1);
  }
}
È stato utile?

Soluzione

Code coverage doesn't tell you everything. In this case you'll get 100% line coverage for factorial(3) but it won't cover all "cases".

When testing a recursive function you'd want to test various cases:

  • Each of the base cases.
  • The recursive cases.
  • Incorrect input (e.g., negative numbers).
  • Any function-specific edge cases.

You can test less but you'll leave yourself open for potential bugs when the code is changed in the future.

Altri suggerimenti

Technically if you test[well, execute] factorial(2) you also test [execute] factorial(1) if your algorithm is correct.

How would your testing tool know that your code was correct? How would a tester that didn't write the code know your code was correct? The point of "test coverage" is to determine that in fact as much of the code has been tested [well, executed] regardless of whether it is algorithmically correct or not.

A line not executed is a line for which you have no evidence it works. This is what test coverage tells your. The purpose of your tests is to check that the application computes the correct answer. Coverage and tests serve two different purposes. Coverage just happens to take advantage of the fact that tests exercise code.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top