如何测试 .class 文件是否已创建?

发布于 2024-08-11 09:13:49 字数 885 浏览 4 评论 0原文

我想对我的代码进行单元测试,该代码必须创建一个 .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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

孤独患者 2024-08-18 09:13:49

使用 URLClassLoader 的新实例,指向您在其中创建目标类文件的根文件夹。然后,使用 Class.forName(String,ClassLoader); 方法和动态创建的 URLClassLoader 来加载新类。

为了证明它的工作原理,以下测试用例将创建一个源文件,在其中编写一些 Java 代码并使用 Java 6 ToolProvider 接口对其进行编译。然后,它将使用 URLClassLoader 动态加载该类,并调用对其类名的反射调用,以验证它确实是动态生成的类。

@Test
public void testUrlClassLoader() throws Exception {
    Random random = new Random();
    String newClassName = "Foo" + random.nextInt(1000);
    JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
    StandardJavaFileManager fileManager = compiler.getStandardFileManager(null, null, null);
    List<File> files = new ArrayList<File>();
    File sourceFolder = new File(".");
    File sourceFile = new File(sourceFolder, newClassName + ".java");
    FileWriter fileWriter = new FileWriter(sourceFile);
    fileWriter.write("public class " + newClassName + " { { System.out.println(\""
            + newClassName + " loaded\"); }}");
    fileWriter.close();
    files.add(sourceFile);
    Iterable<? extends JavaFileObject> compilationUnits1 = fileManager
            .getJavaFileObjectsFromFiles(files);
    compiler.getTask(null, fileManager, null, null, null, compilationUnits1).call();
    fileManager.close();

    URL url = sourceFolder.toURI().toURL();
    URLClassLoader urlClassLoader = new URLClassLoader(new URL[] { url });
    Object newInstance = urlClassLoader.loadClass(newClassName).newInstance();
    assertEquals(newClassName, newInstance.getClass().getName());
}

Use a new instance of an URLClassLoader, pointing to the root folder where you created the target class file. Then, use the Class.forName(String,ClassLoader); method with the dynamically created URLClassLoader 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.

@Test
public void testUrlClassLoader() throws Exception {
    Random random = new Random();
    String newClassName = "Foo" + random.nextInt(1000);
    JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
    StandardJavaFileManager fileManager = compiler.getStandardFileManager(null, null, null);
    List<File> files = new ArrayList<File>();
    File sourceFolder = new File(".");
    File sourceFile = new File(sourceFolder, newClassName + ".java");
    FileWriter fileWriter = new FileWriter(sourceFile);
    fileWriter.write("public class " + newClassName + " { { System.out.println(\""
            + newClassName + " loaded\"); }}");
    fileWriter.close();
    files.add(sourceFile);
    Iterable<? extends JavaFileObject> compilationUnits1 = fileManager
            .getJavaFileObjectsFromFiles(files);
    compiler.getTask(null, fileManager, null, null, null, compilationUnits1).call();
    fileManager.close();

    URL url = sourceFolder.toURI().toURL();
    URLClassLoader urlClassLoader = new URLClassLoader(new URL[] { url });
    Object newInstance = urlClassLoader.loadClass(newClassName).newInstance();
    assertEquals(newClassName, newInstance.getClass().getName());
}
情归归情 2024-08-18 09:13:49

您可以使用“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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文