我正在研究一个监视目录的程序,并在看到目录中的更改时运行目录中的所有测试.
这需要程序动态加载类,而不是获取缓存副本.
我可以动态加载测试类.在运行时检测并使用对测试的更改.但是,测试所测试的类不是这种情况.
我的代码用于动态加载类并返回测试类列表:
List> classes = new ArrayList>();
for (File file : classFiles) {
String fullName = file.getPath();
String name = fullName.substring(fullName.indexOf("bin")+4)
.replace('/', '.')
.replace('\', '.');
name = name.substring(0, name.length() - 6);
tempClass = new DynamicClassLoader(Thread.currentThread().getContextClassLoader()).findClass(name) } catch (ClassNotFoundException e1) {
// TODO Decide how to handle exception
e1.printStackTrace();
}
boolean cHasTestMethods = false;
for(Method method: tempClass.getMethods()){
if(method.isAnnotationPresent(Test.class)){
cHasTestMethods = true;
break;
}
}
if (!Modifier.isAbstract(cachedClass.getModifiers()) && cHasTestMethods) {
classes.add(tempClass);
}
}
return classes;
知道怎么解决吗?我以为所有类都会动态加载.但请注意,我不会覆盖DynamicClassLoader中的loadclass,因为如果我执行测试类,则给出init
编辑:
这不起作用,类被加载但未检测到其中的测试…
List requests = new ArrayList();
for (File file : classFiles) {
String fullName = file.getPath();
String name = fullName.substring(fullName.indexOf("bin")+4)
.replace('/', '.')
.replace('\', '.');
name = name.substring(0, name.length() - 6);
Class> cachedClass = null;
Class> dynamicClass = null;
try {
cachedClass = Class.forName(name);
URL[] urls={ cachedClass.getProtectionDomain().getCodeSource().getLocation() };
ClassLoader delegateParent = cachedClass .getClassLoader().getParent();
URLClassLoader cl = new URLClassLoader(urls, delegateParent) ;
dynamicClass = cl.loadClass(name);
System.out.println(dynamicClass);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
编辑编辑:我检测到这样的测试方法:
for(Method method: dynamicClass.getMethods()){
if(method.isAnnotationPresent(Test.class)){
requests.add(Request.method(dynamicClass, method.getName()));
}
}