How to add Suite-level setUp and tearDown methods to an existing Junit TestCase
Use the following helper class:
package biz.wss.test.junit;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
import junit.extensions.TestSetup;
/**
* Add working suite-level lifecycle methods to a Test.
*/
public class TestSuiteHelper {
private Test suite;
public TestSuiteHelper() {
// Don't ya just love a good hack ;-)
String testClassName = new Exception().getStackTrace()[1].getClassName() ;
try {
Class<? extends TestCase> testClass = ((Class<? extends TestCase>)Class.forName(testClassName));
this.suite = new LifecycleWrapper(testClass);
} catch (Exception ex) {
throw new IllegalStateException("TestSuiteHelper() should be invoked directly from public static Test suite()");
}
}
public Test suite() {
return this.suite;
}
private class LifecycleWrapper extends TestSetup {
private Method suiteSetUp;
private Method suiteTearDown;
public LifecycleWrapper(Class<? extends TestCase> test) {
super(new TestSuite(test));
this.suiteSetUp = findMethod(test, "onSuiteSetUp");
this.suiteTearDown = findMethod(test, "onSuiteTearDown");
}
private Method findMethod(Class<?> clazz, String name) {
Method method = null;
while (clazz != null && TestCase.class.isAssignableFrom(clazz)) {
for (Method each : clazz.getDeclaredMethods()) {
if (isRequiredMethod(each, name)) {
method = each;
break;
}
}
clazz = clazz.getSuperclass();
}
return method;
}
private boolean isRequiredMethod(Method m, String name) {
int mods = m.getModifiers();
return (Modifier.isPublic(mods) &&
Modifier.isStatic(mods) &&
m.getParameterTypes().length == 0 &&
m.getName().equals(name) &&
m.getReturnType().equals(Void.TYPE));
}
public void setUp() throws Exception {
if (this.suiteSetUp != null) {
this.suiteSetUp.invoke(null);
}
}
public void tearDown() throws Exception {
if (this.suiteTearDown != null) {
this.suiteTearDown.invoke(null);
}
}
}
}
Then add a suite()
method to your TestCase as follows.
import junit.framework.TestCase;
public class MyTest extends TestCase {
public static Test suite() {
TestSuiteHelper helper = new TestSuiteHelper();
return helper.suite();
}
public static void onSuiteSetUp() throws Exception {
System.err.println("onSuiteSetUp");
}
public static void onSuiteTearDown() throws Exception {
System.err.println("onSuiteTearDown");
}
public void setUp() throws Exception {
System.out.println("per-test setUp");
}
public void tearDown() throws Exception {
System.out.println("per-test tearDown");
}
public void testOne() throws Exception {
System.out.println("testOne");
}
public void testTwo() throws Exception {
System.out.println("testTwo");
}
public void testThree() throws Exception {
System.out.println("testThree");
}
}
The new onSuiteSetUp()
and onSuiteTearDown()
methods will be invoked at the appropriate time.