When you need to test something, here is what you do:
@Test public void simpleAdd() { Money m12CHF= new Money(12, "CHF"); Money m14CHF= new Money(14, "CHF"); Money expected= new Money(26, "CHF"); Money result= m12CHF.add(m14CHF); assertTrue(expected.equals(result)); }
Tests need to run against the background of a known set of objects. This set of objects is called a test fixture.
When you have a common fixture, here is what you do:
public class MoneyTest { private Money f12CHF; private Money f14CHF; private Money f28USD; @Before public void setUp() { f12CHF= new Money(12, "CHF"); f14CHF= new Money(14, "CHF"); f28USD= new Money(28, "USD"); } }
Once you have tests, you'll want to run them. JUnit provides tools to define the suite to be run and to display its results. To run tests and see the results on the console, run this from a Java program:
or this from the command line, with both your test class and junit on the classpath:org.junit.runner.JUnitCore.runClasses(TestClass1.class, ...);
java org.junit.runner.JUnitCore TestClass1 [...other test classes...]
For example:
This code should throw an IndexOutOfBoundsException. The @Test annotation has an optional parameter "expected" that takes as values subclasses of Throwable. If we wanted to verify that ArrayList throws the correct exception, we would write:new ArrayList<Object>().get(0);
@Test(expected= IndexOutOfBoundsException.class) public void empty() { new ArrayList<Object>().get(0); }