JMU
JUnit v4
An Introduction


Prof. David Bernstein
James Madison University

Computer Science Department
bernstdh@jmu.edu


Background
Creating Test Classes
Some assert___() Methods
An Example
An Example (cont.)
import static org.junit.Assert.*;

import org.junit.Test;

public class AtomTest
{
    @Test
    public void testGetAtomicNumber()
    {
        // Setup - Declare and construct an Atom for oxygen
        Atom    o;

        o = new Atom("O", 8, 16);
  

        // This is a call to Assert.assertEquals() but the class name
	// isn't needed because of the static import.
        //
        // It checks that the value returned by getAtomicNumber() is
        // equal to 8 (as it should be)
        assertEquals("Oxygen", 8, o.getAtomicNumber());
    }


    @Test
    public void testEquals()
    {
	// Setup - Declare and construct an Atom for oxygen and two
	// for hydrogen
        Atom    h, hh, o;
  
        h  = new Atom("H", 1, 1);
        hh = new Atom("H", 1, 1);
        o  = new Atom("O", 8, 16);

        // Compare two Atom objects that should be the same
        assertTrue("Two H atoms", h.equals(hh));

        // Compare two Atom objects that should be different  
        assertFalse("H and O", h.equals(o));
        assertFalse("O and H", o.equals(h));
    }
}
  
Testing Methods that Throw Exceptions
An Example (cont.)
An Example (cont.)
  @Test(expected = IllegalArgumentException.class)
  public void testConstructor_IllegalArguments()
  {
    Atom    o;
  
    o = new Atom("O", -8, -16);
  }
  
Common Setup/Cleanup
Common Setup/Cleanup (cont.)
Some Notes About Terminology
Executing JUnit Tests