go to previous page   go to home page   go to next page

Answer:

Yes.


Unit Testing

Some programming environments (such as BlueJ) let you test individual methods. This can be very useful. This is called unit testing because just one unit (just one module) can be thoroughly tested by itself. Again, test modules as soon as possible. Testing only after until everything has been put together can be hopeless.

With the command line interface used in our examples you need a main() to drive the method. Here is a unit test of our method:

Edit N in main() for various test runs to check that the method works for each. Values to check are 0, 1, 2, 6, 20, -1, -2. It is important to test 0, 1, and -1 since it is at the "boundaries" that methods often go wrong.

Actually, our original main() is itself a good testing framework for factorial() and you would probably not bother with the code below. But sometimes a thorny debugging problem calls for a bare-bones main().

(If you want a complete, working program, replace the stub factorial in the full main with the non-stub factorial below.)


public class UnitTest
{
  
  public static long factorial( int num )
  {
    long fct = 1;
    for ( int j=1; j<=num; j++ )
      fct *= j;
    return fct;
  }
  
  public static void main (String[] args ) 
  {
     int N = 6;
     System.out.println( "factorial of " + N + ": " + factorial( N ) );
  }
}

QUESTION 8:

In the course of unit testing, a programmer changes N to 21 and sees

factorial of 21: -4249290049419214848

A NEGATIVE value!

What went wrong?


go to previous page   go to home page   go to next page