使用classloader自定义测试套件TestSuite

junit自带了一个suite用来将多个test case放在一起执行, 但是有时候test case太多, 或者每次只需要对特定的几个test case进行测试, 这样写就比较繁琐, 于是希望通过一种带有通配符的表达式来指定需要测试的某些符合条件的test case, 于是根据这个需求, 实现了一个自己的PathSuite, 不过目前还比较简单, 关键是表达式的解析实现比较难搞, 不知道有没有现成的类似的通配符表达式可用? 反正我是没有找到:(
这里需要借助ClassLoader用来加载指定的class文件, 因为通过表达式得到的只是一些文件路径, 要将指定的路径转换成class定义以及类实例就需要借助ClassLoader, 当然这里使用的都是ClassLoader非常简单的功能.
/**
 * <p>
* 使用Junit Runner运行指定package下所有的*Test.java测试类或者指定的类.
* </p>
* 目前只支持形如
* <ul>
* <li>"com.mysoft.item.test.*"匹配整个package</li>
* <li>"com.mysoft.item.test.*ATest.class",匹配整个package下的某些文件(未实现)</li>
* <li>"com.mysoft.item.test.**", 匹配整个package以及子package(未实现)</li>
* <li>"com.mysoft.item.test.internal.CTest.class"匹配单个文件</li>
* </ul>
* 的表达式
 * @since 2009-10-14 下午06:00:12
 */
public class PathSuite extends CompositeRunner {
    private TestClass fTestClass;
    private final static String classSuffix = ".class";

    @Retention(RetentionPolicy.RUNTIME)
    @Target(ElementType.TYPE)
    public @interface Paths {
        /**
         * 指定需要运行的测试目录或测试类
         * @return
         */
        public String[] value();

        /**
         * 指定那些不需要运行的测试目录或测试类(未实现)
         * @return
         */
        public String[] exclude() default {};
    }

    public PathSuite(Class<?> klass) throws InitializationError {
        super(klass.getSimpleName());

        Class<?>[] annotatedClasses = getAnnotatedClasses(klass);
        for (Class<?> each : annotatedClasses) {
            Runner childRunner = Request.aClass(each).getRunner();
            if (childRunner != null)
                add(childRunner);
        }

        fTestClass = new TestClass(klass);
        MethodValidator methodValidator = new MethodValidator(fTestClass);
        methodValidator.validateStaticMethods();
        methodValidator.assertValid();
    }

    private static Class<?>[] getAnnotatedClasses(Class<?> klass) throws InitializationError {
        Paths annotation = klass.getAnnotation(Paths.class);
        if (annotation == null)
            throw new InitializationError(String.format("class '%s' must have a Paths annotation", klass
                    .getName()));

        return getTestClasses(annotation.value());
    }

    private static Class<?>[] getTestClasses(String[] testClassPaths) {
        List<String> classNames = getClassNames(testClassPaths);

        ClassLoader loader = new TestClassLoader();
        List<Class<?>> classes = new ArrayList<Class<?>>();
        for (String className : classNames) {
            try {
                Class<?> clazz = loader.loadClass(className);
                // 去掉抽象类
                if (Modifier.isAbstract(clazz.getModifiers())) {
                    continue;
                }
                classes.add(clazz);
            } catch (Exception e) {
                throw new RuntimeException(String.format("加载测试类[%s]失败", className), e);
            }
        }

        return classes.toArray(new Class<?>[0]);
    }

    private static List<String> getClassNames(String[] testClassPaths) {
        List<String> classNames = new ArrayList<String>();
        for (String testClassPath : testClassPaths) {
            // com.mysoft.item.test.*
            if (StringUtils.isBlank(testClassPath)) {
                continue;
            }
            String packagePrefix = testClassPath.replaceAll("\\*.*", "");
            if (isClass(testClassPath)) {
                // com.mysoft.item.test.ATest.class

                // com.mysoft.item.test.ATest
                testClassPath = testClassPath.replaceFirst("\\.class", "");
                // com.mysoft.item.test
                packagePrefix = testClassPath.substring(0, testClassPath.lastIndexOf(".") + 1);

                // com/mysoft/item/test/ATest.class
                testClassPath = testClassPath.replace(".", "/") + classSuffix;
            } else {
                // com.mysoft.item.test.
                packagePrefix = testClassPath.replaceAll("\\*.*", "");
                // com/mysoft/item/test/*
                testClassPath = testClassPath.replace(".", "/");
            }


            classNames.addAll(getClassNames(testClassPath, packagePrefix));
        }
        return classNames;
    }

    private static boolean isClass(String testClassPath) {
        return testClassPath.endsWith(classSuffix);
    }

    private static List<String> getClassNames(String path,
            String packagePrefix) {
        // com/mysoft/item/test
        path = path.replaceFirst("\\/\\*$", "");

        String absolutePath = PathUtils.getAbsolutePath(path);

        return findClasses(packagePrefix, new File(absolutePath));
    }

    private static List<String> findClasses(String packagePrefix, File folder) {
        List<String> result = new ArrayList<String>();
        if (folder.isDirectory()) {
            // 得到里面的每一个class文件
            File[] testClasses = folder.listFiles(new FilenameFilter() {
                public boolean accept(File dir, String name) {
                    return name.endsWith("Test.class");
                }
            });

            for (File file : testClasses) {
                result.add(getClassName(packagePrefix, file));
            }
        } else {
            result.add(getClassName(packagePrefix, folder));
        }
        return result;
    }

    private static String getClassName(String packagePrefix, File file) {
        return packagePrefix + file.getName().replaceFirst("\\.class", "");

    }
}



TestClassLoader的实现, 这个是从网上找来的一个类似的实现做了些改动, 可以凑合着用用^_^, 不过大部分ClassLoader差不多都这样用
/**
* 用来加载当前classpath下的Test Class
 * @since 2009-10-21 下午03:46:34
 */
public class TestClassLoader extends ClassLoader {

    /**
     * @param name 形如"java.lang.String"的字符串
     * {@inheritDoc} 
     */
    @Override
    protected Class<?> findClass(String name)
            throws ClassNotFoundException {
        byte[] bytes = loadClassBytes(name);
        Class<?> theClass = defineClass(name, bytes, 0, bytes.length);// A
        if (theClass == null)
            throw new ClassFormatError();
        return theClass;
    }

    private byte[] loadClassBytes(String className) throws
            ClassNotFoundException {
        try {
            String classFile = getClassFile(className);
            FileInputStream fis = new FileInputStream(classFile);
            FileChannel fileC = fis.getChannel();
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            WritableByteChannel outC = Channels.newChannel(baos);
            ByteBuffer buffer = ByteBuffer.allocateDirect(1024);
            while (true) {
                int i = fileC.read(buffer);
                if (i == 0 || i == -1) {
                    break;
                }
                buffer.flip();
                outC.write(buffer);
                buffer.clear();
            }
            fis.close();
            return baos.toByteArray();
        } catch (IOException fnfe) {
            throw new ClassNotFoundException(className);
        }
    }

    private String getClassFile(String name) {
        StringBuffer sb = new StringBuffer(getBaseDir());
        name = name.replace('.', File.separatorChar) + ".class";
        sb.append(File.separator + name);
        return sb.toString();
    }

    private String getBaseDir() {
        return TestClassLoader.class.getResource(File.pathSeparator).toString();
    }

    // 新增的一个findResource方法
    @Override
    protected URL findResource(String name) {
        try {
            URL url = super.findResource(name);
            if (url != null)
                return url;
            url = new URL("file:///" + converName(name));
            // 简化处理,所有资源从文件系统中获取
            return url;
        } catch (MalformedURLException mue) {
            throw new RuntimeException(mue);
        }
    }

    private String converName(String name) {
        StringBuffer sb = new StringBuffer(getBaseDir());
        name = name.replace('.', File.separatorChar);
        sb.append(File.separator + name);
        return sb.toString();
    }
}



这里只是为了演示classloader的用法, 其实根本没有必要这么复杂, 其中
Class<?> clazz = loader.loadClass(className);

这一句, 可以简单的使用
Class<?> clazz = Class.forName(className);

代替搞定.
另外eclipse也可以直接选中指定的package运行里面所有的test case, 我也是最近从测试人员那里知晓的:(

你可能感兴趣的:(eclipse,JUnit)