Junit Example
From RifidiWiki
Junit 4.x may be tricky at first to build test suites or regular tests, but they are pretty easy to write once one gains a hang of it.
Here is an example of a regular test class.
import org.junit.AfterClass;
import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.Test;
public class Example {
@BeforeClass
public static void setUpBeforeClass() throws Exception {
/* things to do before running tests */
}
@AfterClass
public static void tearDownAfterClass() throws Exception {
/* things to do after running tests */
}
@Test
public void testExample1() {
}
@Test
public void testExample2() {
}
}
Here is an example of a test suite. This class can be subclassed to create sub-suites to keep from writing
boiler plate code over and over.
import java.util.ArrayList;
import org.junit.runner.Description;
import org.junit.runner.RunWith;
import org.junit.runner.Runner;
import org.junit.runner.notification.RunNotifier;
/*
* This is the runner class for the entire test suite.
* All we do here is to add the sub suites here.
*
* This class can be subclassed to create subsuites.
* Note the run with annotation is needed for each subsuite.
* And each subsuite must have a constructor with a signature of
* public [constructor] (Class<?> klass)
*/
@RunWith(SuiteExample.class)
public class SuiteExample extends Runner {
protected Description description;
protected ArrayList<Runner> runners;
public ReaderTests()
{
runners = new ArrayList<Runner>();
};
public ReaderTests (Class<?> klass)
{
this();
runners.add(Request.aClass(Example.class).sortWith(this).getRunner());
description = Description.createSuiteDescription("Rifidi Junit Test Suite");
addRunnersToDescription();
}
/* call this method in the constructor of the subclass
* to add the runners to the description
*/
protected void addRunnersToDescription()
{
for(Runner run : runners)
{
description.addChild(run.getDescription());
}
}
@Override
public Description getDescription() {
return description;
}
@Override
public void run(RunNotifier notifier) {
notifier.fireTestStarted(description);
for (Runner run : runners)
{
notifier.fireTestStarted(run.getDescription());
run.run(notifier);
notifier.fireTestFinished(run.getDescription());
}
notifier.fireTestFinished(description);
}
}