JMU
JUnit v5 (Jupiter)
An Introduction


Prof. David Bernstein
James Madison University

Computer Science Department
bernstdh@jmu.edu


Background
Creating Test Classes
Some assert___() Methods
Some assert___() Methods (cont.)
An Example
An Example (cont.)
import static org.junit.jupiter.api.Assertions.*;
 
import org.junit.jupiter.api.Test;
 
public class AtomTest
{
   /**
     * Unit tests for the getAtomicNumber() method
     */
    @Test
    public void getAtomicNumber_Test()
    {
        Atom    o;
 
        o = new Atom("O", 8, 16);
 
        assertEquals(8, o.getAtomicNumber(), "Oxygen");
	// Note:
        // This is a call to Assertions.assertEquals() but the class name
	// isn't needed because of the static import.
    }

    /**
     * Unit tests for the equals(Atom) method
     */
    @Test
    public void equals_Test()
    {
      Atom    h, hh, o;
 
      h  = new Atom("H", 1, 1);
      hh = new Atom("H", 1, 1);
      o  = new Atom("O", 8, 16);
 
      assertTrue(h.equals(hh), "Two H atoms");
 
      assertFalse(h.equals(o), "H and O");
      assertFalse(o.equals(h), "O and H");
    } 
}
  
Testing Methods that Throw Exceptions
An Example (cont.)
An Example (cont.)
  /**
   * Test that the constructor validates properly.
   */
  @Test
  public void constructor_IllegalArguments() 
          throws IllegalArgumentException
  {
    assertThrows(IllegalArgumentException.class, 
                 () -> {new Atom("O", -8, -16);});
  }
  
An Easier Approach for Beginning Programmers
  /**
   * Test that the constructor validates properly.
   */
  @Test
  public void constructor_IllegalArguments()
  {
    try
    {
      new Atom("O", -8, -16);
 
      // Shouldn't get here
      fail("Constructor should have thrown an IllegalArgumentException");
    }
    catch (IllegalArgumentException iae)
    {
      // The exception was thrown as expected
    }   
  }
  
Common Setup/Cleanup
Common Setup/Cleanup (cont.)
Some Notes About Terminology
Executing JUnit Tests