gpt4 book ai didi

java - JUnitCore 不加载测试用例所需的库

转载 作者:行者123 更新时间:2023-11-30 11:46:43 25 4
gpt4 key购买 nike

我正在尝试编写一个动态运行外部类测试的方法。我能够运行仅使用 JDK 库的测试,但是当我运行使用另一个库(例如 org.jmock.Mockery)的测试时,JUnitCore.run(args) 返回的结果对象出现以下错误:

[initializationError(package.TestClass): org/jmock/Mockery]
java.lang.NoClassDefFoundError: org/jmock/Mockery

com.sun.jdi.ClassNotLoadedException: Type has not been loaded occurred while retrieving component type of array.

不用说,如果我从他们在 eclipse 中的原始项目运行测试,测试就会运行并通过。

我认为问题与类路径有关,因为 ClassLoader 似乎只加载被测试的类,而不加载外部项目类路径中定义的依赖项(如 jars)。我不知道如何将 jars 动态加载到正在执行的应用程序。

下面是加载类和运行测试的代码。

URL url = new File("E:\eclipseProjectName\bin\").toURL();
final URL[] urls = new URL[] { url };
final ClassLoader cl = new URLClassLoader(urls);
@SuppressWarnings("rawtypes")
final Class cls = cl.loadClass("package.ClassName");
final JUnitCore core = new JUnitCore();
final Result result = new JUnitCore().run(Request.method(cls, "methodName"));

提前致谢

马克·卡奇亚

最佳答案

如果您想在运行测试的应用程序中加载您正在使用的库,您需要设置您的 URLClassLoader 以加载您当前的类加载器,然后引用您所在的类尝试测试

 URLClassLoader cl = new URLClassLoader(classLoaderUrls, getClass().getClassLoader());

这是一个从 jar 动态加载类的示例。如果您只想按名称加载您的一个类,您可以像上面那样做。

    File pathToJar = new File(jarPath);

JarFile jarFile;
jarFile = new JarFile(pathToJar);
Enumeration<JarEntry> e = jarFile.entries();

URL[] classLoaderUrls = new URL[]{pathToJar.toURI().toURL()};

URLClassLoader cl = new URLClassLoader(classLoaderUrls, getClass().getClassLoader());
while (e.hasMoreElements()) {

// load all the classes in the jar (or you can set it up to use the exact class/method name as you did above
JarEntry je = e.nextElement();
if(je.isDirectory() || !je.getName().endsWith(".class")){
continue;
}
// -6 because of .class
String className = je.getName().substring(0,je.getName().length()-6);
className = className.replace('/', '.');
Class c = cl.loadClass(className);


JUnitCore junit = new JUnitCore();
Result result = junit.runClasses(c);
// check for failed/ passed tests here

}

关于java - JUnitCore 不加载测试用例所需的库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9634252/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com