1 package test.mockobjects; 2 import java.io.File ; 3 import java.lang.reflect.Modifier ; 4 import java.util.StringTokenizer ; 5 import junit.framework.*; 6 7 8 11 public class AutoTestSuite 12 extends TestSuite 13 { 14 17 public AutoTestSuite() { 18 super("System Tests"); 19 20 String class_path= System.getProperty("java.class.path"); 21 String separator= System.getProperty("path.separator"); 22 StringTokenizer path_elements = 23 new StringTokenizer ( class_path, separator ); 24 25 while( path_elements.hasMoreTokens() ) { 26 File root = new File ( path_elements.nextToken() ); 27 28 if( root.isDirectory() ) { 29 TestSuite sub_suite = 30 new AutoTestSuite( root.toString(), root, root ); 31 32 if( sub_suite.testCount() > 0 ) addTest( sub_suite ); 33 } 34 } 35 } 36 37 private AutoTestSuite( String name, File root, File dir ) { 38 super( name ); 39 40 File [] contents = dir.listFiles(); 41 42 for( int i = 0; i < contents.length; i++ ) { 43 File f = contents[i]; 44 45 if( f.isDirectory() ) { 46 addNonEmptySuite(new AutoTestSuite( f.getName(), root, f )); 47 48 } else if( isTestClass(f) ) { 49 try { 50 Class test_class = fileToClass( root, f ); 51 if( isInstantiable(test_class) ) { 52 addNonEmptySuite(new TestSuite(test_class)); 53 } 54 } 55 catch( ClassNotFoundException ex ) { 56 System.err.println("failed to load class " + f ); 57 ex.printStackTrace(); 58 } 60 } 61 } 62 } 63 64 private void addNonEmptySuite(TestSuite suite) { 65 if( suite.testCount() > 0 ) { 66 addTest( suite ); 67 } 68 } 69 70 private boolean isInstantiable( Class c ) { 71 int mods = c.getModifiers(); 72 73 return !Modifier.isAbstract(mods) && 74 !Modifier.isInterface(mods) && 75 Modifier.isPublic(mods); 76 } 77 78 80 protected boolean isTestClass( File f ) { 81 String name = f.getName(); 82 return name.endsWith("Test.class") || 83 ( name.endsWith(".class") && 84 name.startsWith("Test") && 85 !isFilenameOfInnerClass(name) ); 86 } 87 88 private boolean isFilenameOfInnerClass(String name) { 89 return name.indexOf('$') >= 0; 90 } 91 92 private Class fileToClass( File root, File f ) 93 throws ClassNotFoundException 94 { 95 String class_name = pathToClassName( root.toString(), f.toString() ); 96 return Class.forName( class_name ); 97 } 98 99 private String pathToClassName( String root, String f ) { 100 int root_len = root.length(); 101 if( !root.endsWith("/") ) root_len++; 102 int tail_len = f.length() - ".class".length(); 103 104 return f.substring( root_len, tail_len ).replace('/','.'); 105 } 106 107 109 public static TestSuite suite() { 110 return new AutoTestSuite(); 111 } 112 113 public static void main( String [] args ) { 114 junit.swingui.TestRunner.main( new String []{ 115 AutoTestSuite.class.getName() 116 } ); 117 } 118 } 119 | Popular Tags |