JUnit 4 Learning Test

by David Janzen


Unit tests can be used to explore how to use existing code such as Java library functions. Suppose we want to learn how Java's ArrayList works. We might write some learning tests like TestArrayList.java below. Notice how the assertEquals() method can take three arguments where the third argument is the delta (i.e. the first two arguments are expected to be equal within this level of precision).

Copy this class into your editor, compile and run the JUnit tests. If you need the test suite, AllTests.java is provided below.

After you have these tests passing correctly, try to write some additional tests. For instance, create a test that adds String's to an ArrayList of Strings. Or add a test that inserts double values wrapped in the Double wrapper class. Or add a test that attempts to access the fourth element in an ArrayList that only has three elements.

TestArrayList.java

import static org.junit.Assert.*;
import org.junit.Test;
import java.util.ArrayList;


public class TestArrayList 
{
	
   @Test
   public void testEmptyArrayList() 
   {
      ArrayList<Integer> al = new ArrayList<Integer>();
      assertEquals (al.size(),0);
   }

   @Test
   public void testIntArrayList()
   {
      ArrayList<Integer> al = new ArrayList<Integer>();
      al.add(5);
      al.add(-14);
      al.add(29);
      assertEquals(al.size(),3);
      assertEquals(al.get(0),5);
      assertEquals(al.get(1),-14);
      assertEquals(al.get(2),29);
   }

   @Test
   public void testDoubleArrayList()
   {
      ArrayList<Double> al = new ArrayList<Double>();
      al.add(5.9);
      al.add(-14.26789);
      al.add(29.0);
      al.add(0.00456);
      assertEquals(al.size(),4);
      assertEquals(al.get(0),5.9,0.001);
      assertEquals(al.get(1),-14.26789,0.001);
      assertEquals(al.get(2),29.0,0.001);
      assertEquals(al.get(3),0.00456,0.00001);
   }

}

AllTests.java

import org.junit.runner.RunWith;
import org.junit.runners.Suite;
import junit.framework.JUnit4TestAdapter;

// This section declares all of the test classes in your program.
@RunWith(Suite.class)
@Suite.SuiteClasses({
   TestArrayList.class  // Add test classes here.
})

public class AllTests 
{
   //This can be empty if you are using an IDE that includes support for JUnit
   //such as Eclipse.  However, if you are using Java on the command line or
   //with a simpler IDE like JGrasp or jCreator, the following main() and suite()
   //might be helpful.

   // Execution begins at main().  In this test class, we will execute
   // a text test runner that will tell you if any of your tests fail.
   public static void main (String[] args) 
   {
      junit.textui.TestRunner.run (suite());
   }

   // The suite() method is helpful when using JUnit 3 Test Runners or Ant.
   public static junit.framework.Test suite() 
   {
      return new JUnit4TestAdapter(AllTests.class);
   }

}