java - 如何从 junit 中的 java 扩展文件中读取和测试类?我怎样才能访问该类进行测试?

标签 java testing junit mutation-testing

在一个变异测试软件中,创建了很多java扩展文件的变异体(如mutant01.java)。现在我需要使用 jUnit4 测试这些文件。我试图找出能够读取文件然后从该文件访问特定类并对它执行 jUnit 测试的方法。但我需要帮助吗?

我发现了一些方法只会导致我的文件被上传,但我无法访问该文件的内容或特定类。

@Test
public void testReadFileWithClassLoader(){
    try {
        ClassLoader classLoader = this.getClass().getClassLoader();
        File file = new File(classLoader.getResource("arith.java").getFile());
        Class<? extends File> f=file.getClass();
        assertTrue(file.exists());

我希望我能够从 java 扩展文件访问该类,然后对其执行 junit 测试,但实际上我被困住了。

最佳答案

AS @John Mercier 指出你必须先编译你的类然后加载它。你可以使用 jOOR为了更容易做到这一点。

jOOR - Fluent Reflection in Java jOOR is a very simple fluent API that gives access to your Java Class structures in a more intuitive way. The JDK's reflection APIs are hard and verbose to use. Other languages have much simpler constructs to access type meta information at runtime. Let us make Java reflection better.

用于 Java 9+

<dependency>
  <groupId>org.jooq</groupId>
  <artifactId>joor</artifactId>
  <version>0.9.7</version>
</dependency>

用于 Java 8+

<dependency>
  <groupId>org.jooq</groupId>
  <artifactId>joor-java-8</artifactId>
  <version>0.9.7</version>
</dependency>

用于 Java 6+

<dependency>
  <groupId>org.jooq</groupId>
  <artifactId>joor-java-6</artifactId>
  <version>0.9.7</version>
</dependency>

使用示例:

Supplier<String> supplier = Reflect.compile(
    "com.example.HelloWorld",
    "package com.example;\n" +
    "class HelloWorld implements java.util.function.Supplier<String> {\n" +
    "    public String get() {\n" +
    "        return \"Hello World!\";\n" +
    "    }\n" +
    "}\n").create().get();

// Prints "Hello World!"
System.out.println(supplier.get());

请注意,您必须先读取您的 .java 文件作为字符串

关于java - 如何从 junit 中的 java 扩展文件中读取和测试类?我怎样才能访问该类进行测试?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57315704/

相关文章:

flutter - 如何为 `extending a class` 编写有意义的测试?

java - JUnit 如何找到测试?

java - 如何获取i值并执行点击操作?

java - 类继承的数组值限制

ruby - 检查测试是否失败并相应地给出控制台输出

ant - 使用 <junit> Ant Task 立即进行 JUnit 测试日志记录

java - easymock 如何模拟/设置公共(public)最终变量

java.lang.IllegalArgumentException : argument type mismatch:when store the form values in Database 异常

java - ActionListener 没有响应 [示例]

javascript - 在远程开发服务器上使用 Cypress 测试运行程序