JUnit Cheat Sheet
Writing a basic test suite
import junit.framework.TestCase;
import junit.framework.Test;
import junit.framework.TestSuite;
import junit.textui.TestRunner;
public class MyTestSuite extends TestCase {
public void aTest() {
// test expected and actual with .equals()
assertEquals("describe failure", expected, actual);
// test expected and actual with == operator
assertSame(message,expected,actual);
}
// assert that foobar is null
assertNull(m,foobar);
// assert that barfoo isn't null
assertNotNull(message,barfoo);
}
public void anotherTest() {
// assert that code shouldn't reach next line:
fail("shouldn't get here");
}
}
Composing test suites
Within a TestCase class write:
public static Test suite() {
TestSuite suite = new TestSuite();
// new way to add test suites:
suite.addTestSuite(MyTestingClass.class);
suite.addTestSuite(AnotherTestingClass.class);
// verbose old way to add test suites:
suite.addTest(new TestSuite(YetAnotherTestingClass.class));
return suite;
}
// to make the class directly runnable insert:
public static void main(String args[]) {
junit.textui.TestRunner.run(suite());
}
Using fixtures
A fixture is a group of objects used in several test cases.
Inside the TestSuite class write these methods:
...
public void setUp() {
// create and initialise objects for common use
}
public void tearDown() {
// release resources from objects and remove any references to them
}
...
Errors and Failures
Failure - when some assertion was found to be untrue
Error - an error other than a failed assertion (e.g. a RuntimeException was thrown)
See also
- The JUnit Cookbook: http://junit.sourceforge.net/doc/cookbook/cookbook.htm
- Kent Beck, Test Driven Development: By Example