import java.util.List; import java.util.ArrayList; import java.util.Iterator; import java.lang.reflect.*; public class UnitTester { /** testClass is the class that contains the testcases */ private Class testClass; /** testMethods is an vector of the methods that contain * consists the tests to be executed */ private List testMethods; /** test object is an instance of testClass. */ private Object testObject; /** Set the class to be testet. The className must be a name in classpath. */ private void setClass(String className) throws ClassNotFoundException, InstantiationException, IllegalAccessException { testClass = Class.forName(className); testObject = testClass.newInstance(); } /**get the methods in testClass that take no arguments, and have * a methodName that starts with "test". */ private void getMethods(){ testMethods = new ArrayList(); try{ Method[] allMethods = testClass.getMethods(); for (Method m : allMethods){ if ( m.getName().startsWith("test")){ testMethods.add(m); } } }catch(SecurityException whatWasThat){} } /** execute all the testMethods, and report the result */ private String performTests(){ String result = "Test of " + testClass.getName() + "\n"; for ( Method m : testMethods ){ try{ m.invoke(testObject, new Object[0]); result += m.getName() + " OK\n"; }catch(InvocationTargetException uups){ Throwable target = uups.getTargetException(); if ( target instanceof TestClass.CheckFailure) result += m.getName() +" Check failed: " + ((TestClass.CheckFailure)target).msg + "\n"; else result += m.getName() + " Exception: " + target.toString() + "\n"; } catch(Exception oops){result += oops;} } return result; } public static String testTheClass(String name){ try{ UnitTester ut = new UnitTester(); ut.setClass(name); ut.getMethods(); return ut.performTests(); }catch(Exception uups){ return "Could not find class " + name + "\n" + uups; } } }