Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

TestCase is the base class for writing tests using the JUnit package.

Test and TestSuite provide classes for the framework to create testable objects from your test case.

All test cases need to extend the TestCase class so that JUnit knows that the class provides a test case.

No Format
public class TestCaseExample extends TestCase

The constructor for this class should be public, or JUnit cannot access it.

No Format

public void TestCaseExample() throws Exception

The suite() function is necessary boilerplate for JUnit. Replace "TestCaseExample" with the actual name of your class.

Test cases in org.lcsim need to implement this function as follows.

No Format

public static Test suite()
{
  return new TestSuite(TestCaseExample.class);
}

If your test case requires setup for all its test functions, implement this function, which will be called before any of the tests are executed.

No Format

protected void setUp() throws Exception

Finally, implement individual test cases by writing functions that start with the word "test". JUnit will automatically execute any public function starting with this string.

No Format

public void testIt() throws Exception

Writing Test Statements

The easiest way to make a test is throwing an error when a result does not match an expected quantity.

In Java 1.5, the assert statement can be used.

No Format

assert( results == expected );

In this case, an exception will be thrown if the two variables are not equal. Both results and expected will be printed if this error occurs.

Alternately, an exception can be thrown directly.

No Format

if ( results != expected ) {
  throw new RuntimeException("test failed");
}

If any method or constructor called by your test case throws an exception, the test will fail unless the exception is caught and ignored. In general, test methods should propagate exceptions upward so that failure occurs, unless the exception does not indicate an error. This means that test methods should be declared to throw exceptions.

File and Directory Structure

Maven establishes an organization for tests.

Accessing Test Data using Resources

...