单元测试套件类
代码:
代码:
import java.io.File;
import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
/**
* 单元测试套件类,获取当前包下的所有单元测试类并运行
*
* @author phrash
*
*/
public class AllTests
{
/** 包名 */
private static String pkgName = AllTests.class.getPackage().getName();
/** 测试套件 */
private static TestSuite suite = new TestSuite();
public static Test suite()
{
// 将包名转化为路径,这里也可以具体指明是某个路径
String rPath = pkgName.replace('.', '/') + "/";
// 遍历文件夹下所有文件,并将java文件转化为Class
refreshFileList(rPath, pkgName);
return suite;
}
/**
* 递归获取目录下的class
*
* @param strPath
* @param newPkgName
*/
public static void refreshFileList(String strPath, String newPkgName)
{
// 获取目录
File dir = new File(strPath);
// 获取目录下所有文件和目录
File[] files = dir.listFiles();
if (files == null)
{
return;
}
for (int i = 0; i < files.length; i++)
{
// 文件名
String fileName = files[i].getName();
// 递归
if (files[i].isDirectory())
{
refreshFileList(files[i].getAbsolutePath(), newPkgName + "."
+ fileName);
}
// 判断是不是java文件
else if (-1 != fileName.lastIndexOf(".java"))
{
// 去掉文件名的文件类型后缀
String clsName = fileName.substring(0, fileName
.lastIndexOf("."));
clsName = newPkgName + "." + clsName;
try
{
// 临时Class
Class tempClass = Class.forName(clsName);
// 如果不是测试类则continue
if (!isTestCase(tempClass))
{
continue;
}
// 将得到的Class放入suite中
suite.addTestSuite(tempClass);
} catch (ClassNotFoundException e)
{
e.printStackTrace();
}
}
}
}
/**
* 判断是不是测试类
*
* @param tempClass
* @return boolean
*/
private static boolean isTestCase(Class tempClass)
{
// 如果该类的父类是TestCase,则说明是测试类
if ((tempClass.getSuperclass()).equals(TestCase.class))
{
return true;
}
return false;
}
}