如何测试 .class 文件是否已创建?
我想对我的代码进行单元测试,该代码必须创建一个 .java 文件对其进行编译,然后应创建相应的 .class 文件。
如何创建测试来查看“.class”文件是否已创建?我已经添加了对其存在的测试,现在我正在尝试测试该文件是否是有效的类文件。
我尝试过
try {
Class.forName("Hello");
throw AssertError();
} catch( ClassNotFoundException e ) {
}
program.createClass();
Class.forName("Hello");
但我真的不知道如何动态地将创建文件的路径添加到类路径中。
编辑
加载的 URL 类可以完成这项工作。
这就是我的测试现在的样子。
@Test
void testHello() throws MalformedURLException, ClassNotFoundException {
URL[] url = {
new URL("file:/home/oreyes/testwork/")
};
try {
new URLClassLoader(url).loadClass("Hello");
throw new AssertionError("Should've thrown ClassNotFoundException");
} catch ( ClassNotFoundException cnfe ){
}
c.process();
new URLClassLoader(url).loadClass("Hello");
}
I want to unit test my code which will have to create a .java file compile it and then the corresponding .class file should be created.
How can I create the test to see if the ".class" file is created? I have added test already for its existence, now I'm trying to test the file is a valid class file.
I tried
try {
Class.forName("Hello");
throw AssertError();
} catch( ClassNotFoundException e ) {
}
program.createClass();
Class.forName("Hello");
But I don't really know how to dynamically add the path where the file is created to the classpath.
EDIT
URL Class loaded does the work.
This is how my test looks like now.
@Test
void testHello() throws MalformedURLException, ClassNotFoundException {
URL[] url = {
new URL("file:/home/oreyes/testwork/")
};
try {
new URLClassLoader(url).loadClass("Hello");
throw new AssertionError("Should've thrown ClassNotFoundException");
} catch ( ClassNotFoundException cnfe ){
}
c.process();
new URLClassLoader(url).loadClass("Hello");
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
使用
URLClassLoader
的新实例,指向您在其中创建目标类文件的根文件夹。然后,使用Class.forName(String,ClassLoader);
方法和动态创建的URLClassLoader
来加载新类。为了证明它的工作原理,以下测试用例将创建一个源文件,在其中编写一些 Java 代码并使用 Java 6 ToolProvider 接口对其进行编译。然后,它将使用 URLClassLoader 动态加载该类,并调用对其类名的反射调用,以验证它确实是动态生成的类。
Use a new instance of an
URLClassLoader
, pointing to the root folder where you created the target class file. Then, use theClass.forName(String,ClassLoader);
method with the dynamically createdURLClassLoader
to load the new class.To show that it works, the following test case will create a source file, write some Java code in there and compile it using the Java 6 ToolProvider interfaces. Then, it will dynamically load the class using an URLClassLoader and invoke a reflective call to its class name to verify it's really this class which has been generated on the fly.
您可以使用“file Hello.class”之类的命令来查看它是否报告它是一个 java 类文件,甚至生成一个 java 子进程来加载该类,而不是加载该类来验证它在您的测试 JVM 之外。
Instead of loading the class in order to verify it, you could shell out to a command like "file Hello.class" to see if it reports that it's a java class file, or even spawn a sub-process of java to load the class outside of your test JVM.