SE450: JUnit: Writing A Test [32/41] Previous pageContentsNext page

How do you write a test?

  1. Create an instance of TestCase
  2. Import junit.framework.* and any other classes you need to write your tests
  3. Create a constructor that has a single String argument and passes the argument to the superclass (TestCase). This is optional with JUnit 3.8 and above.
  4. Create a test method for the test you are writing. Make it public and start with the word test (all lower case).
  5. When you want to check a value, call assertTrue and pass in a boolean that is true if the test is successful. You can also use a form of one of the assertEquals, assertFalse, assertNotNull, assertNull assertSame, or assertNotSame from the Assert class.

(Part of) an example that tests the java.util.Vector class.

import junit.framework.*;
import java.util.Vector;

/**
 * A sample test case, testing <code>java.util.Vector</code>.
 *
 */
public class VectorTest extends TestCase {

	public VectorTest(String name) {
	        super(name);
	}

	public void testCapacity() {
	        Vector fEmpty;
	        Vector fFull;

		int size= fFull.size(); 
		for (int i= 0; i < 100; i++)
			fFull.addElement(new Integer(i));
		assertTrue(fFull.size() == 100+size);
	}

Previous pageContentsNext page