JUnit v4
An Introduction |
Prof. David Bernstein |
Computer Science Department |
bernstdh@jmu.edu |
import
statements@Test
)assert___()
methodsassert___()
MethodsAssert.assertEquals([description,] expected, actual)
Assert.assertEquals([description,] expected, actual, tolerance)
Assert.assertEqualsArray([description,] expected, actual[, tolerance])
Assert.assertTrue([description,] actual)
Assert.assertFalse([description,] actual)
Assert.assertNull([description,] actual)
Atom
public int getAtomicNumber()
public boolean equals(Atom other)
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)); } }
expected
element
of the @Test
annotationAtom
constructorIllegalArgumentException
if either of the parameters are negativeassert___()
invokations
after the exception will be thrown@Test(expected = IllegalArgumentException.class) public void testConstructor_IllegalArguments() { Atom o; o = new Atom("O", -8, -16); }
@Before
annotation to indicate that
the method should be invoked before every test method
and the @After
annotation to indicate that
the method should be invoked after every test method
org.junit.Before
and/or org.junit.After
@Before
or
@After
will be invoked
before/after every test methodassert___()
methods are often called
assertions, but they should not be confused with
assert
statements in Javaassert___()
method
can be thought of as an individual test.jar
files in the CLASSPATH
and execute a
"test runner" (commonly org.junit.runner.JUnitCore
)
passing it the name of the test class