JUnit v5 (Jupiter)
An Introduction |
Prof. David Bernstein |
Computer Science Department |
bernstdh@jmu.edu |
import
statements@Test
)assert___()
methodsassert___()
MethodsAssertions.assertEquals(expected, actual [, description] )
Assertions.assertEquals(expected, actual, tolerance [, description] )
Assertions.assertArrayEquals( expected, actual [, tolerance] [,description])
Assertions.assertTrue(actual [, description])
Assertions.assertFalse(actual [, description])
assert___()
Methods (cont.)Assertions.assertSame(expected, actual [, description] )
Assertions.assertNull(actual [, description])
Atom
public int getAtomicNumber()
public boolean equals(Atom other)
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"); } }
assertThrows()
methodAtom
constructorIllegalArgumentException
if either of the parameters are negativeassert___()
invocations
after the exception will be thrown/** * Test that the constructor validates properly. */ @Test public void constructor_IllegalArguments() throws IllegalArgumentException { assertThrows(IllegalArgumentException.class, () -> {new Atom("O", -8, -16);}); }
/** * 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 } }
@BeforeEach
annotation to indicate that
the method should be invoked before every test method
and the @AfterEach
annotation to indicate that
the method should be invoked after every test method
org.junit.jupiter.api.BeforeEach
and/or org.junit.jupiter.api.AfterEach
@BeforeEach
or
@AfterEach
will be invoked
before/after every test methodassert___()
methods are often called
assertions, but they should not be confused with
assert
statements in Java
assert___()
method
can be thought of as an individual test.jar
files in the CLASSPATH
and execute a "test
runner" (commonly
org.junit.platform.console.ConsoleLauncher
)
passing it the name of the test class