SE450: JUnit: Creating a Fixture [33/41] ![]() ![]() ![]() |
A Fixture is just a special TestCase that sets up Objects for the tests to use (and share) for each test. This is done by just overriding a few methods that are part of TestCase. (what do you suppose their visibility is?)
To create a Fixture, add your instance variables and
override setUp
and (if needed)
tearDown
. These methods are called after each
test is executed. setUp
is used to initialize
your variables, tearDown
is used to free up
resources at the end of the test.
(More of) an example that tests the java.util.Vector class.
package junit.samples; import junit.framework.*; import java.util.Vector; import junit.extensions.*; /** * A sample test case, testing <code>java.util.Vector</code>. * */ public class VectorTest extends TestCase { protected Vector fEmpty; protected Vector fFull; protected void setUp() { fEmpty = new Vector(); fFull = new Vector(); fFull.addElement(new Integer(1)); fFull.addElement(new Integer(2)); fFull.addElement(new Integer(3)); } public void testCapacity() { int size= fFull.size(); for (int i= 0; i < 100; i++) fFull.addElement(new Integer(i)); assertTrue(fFull.size() == 100+size); } public void testContains() { assertTrue(fFull.contains(new Integer(1))); assertTrue(!fEmpty.contains(new Integer(1))); } public void testElementAt() { Integer i= (Integer)fFull.elementAt(0); assertTrue(i.intValue() == 1); try { Integer j= (Integer)fFull.elementAt(fFull.size()); } catch (ArrayIndexOutOfBoundsException e) { return; } fail("Should raise an ArrayIndexOutOfBoundsException"); } }