RU beehive logo ITEC dept promo banner
ITEC 120
2009spring
ibarland
nokie
jmdymacek

homeinfolectslabsexamshws
textbooktutor/PIsjava.lang docsjava.util docs

lect03a
writing test methods
and state revisited

Make a test class, class TestRectangle. For several different methods, we'll
  1. read docs;
  2. call interactively (*after* figuring out the expected answer);
  3. write a test case.
Try writing tests several tests for any one of the following methods:

Note: in a test-method, you figure the answers *first*.
Tip: have *some* test cases involving zeroes and ones, whenever applicable.
Mindset: you'll get paid $100 if you find an incorrect result! ...er, rather, you won't lose 20pts (or, your job).

 1  class RectangleTester {
 2      
 3      public static void main( String[] args ) {
 4          java.awt.Rectangle r = new java.awt.Rectangle( 10, 15, 100, 200 );
 5          
 6          r.grow( 5, 7 );
 7          System.out.println( "r's width is now " + r.getWidth() + "; I expected 110." );
 8          System.out.println( "r's height is now " + r.getHeight() + "; I expected 214." );
 9          System.out.println( "r's NW corner is at "
10                            + "(" + r.getX() + "," + r.getY() + ")"
11                            + "; I expected (5,8)." );
12                            
13                            
14          // Also, verify that growing by 0,0 has no effect:
15          r.grow( 0, 0 );
16          System.out.println( "r's width is now " + r.getWidth() + "; I expected 110." );
17          System.out.println( "r's height is now " + r.getHeight() + "; I expected 214." );
18          System.out.println( "r's NW corner is at "
19                            + "(" + r.getX() + "," + r.getY() + ")"
20                            + "; I expected (5,8)." );
21          
22          }
23      
24      }
[download this code]

To test a method

  1. Create an object
  2. call the method to be tested
  3. Compare the result to the expected value. For now, we'll print them.
    If it's a mutator method (which doesn't return a result), then you must call one or more getters after mutating, to make sure the object has changed as expected.
  4. Repeat as necessary.
    (Usually, at least two-three tests are necessary to test a single method.)

Example: BankAccounts

If we had a class BankAccount,

Somebody in the future will actually write class BankAccount. But for now, we'll go ahead and write class BankAccountTester right now!

lect03-BankAccount.jar/ (see how-to-get-jar-files-into-BlueJ—Downloading .jar files into BlueJ).
Observation: We're writing the test-class before we write the actual class! That's the proper way for test-classes to be built.

homeinfolectslabsexamshws
textbooktutor/PIsjava.lang docsjava.util docs


©2009, Ian Barland, Radford University
Last modified 2009.Feb.09 (Mon)
Please mail any suggestions
(incl. typos, broken links)
to iba�rlandrad�ford.edu
Powered by PLT Scheme