简体   繁体   English

如何从junit中的Java扩展文件读取和测试类? 如何访问该类进行测试?

[英]How to read and test a class from java extension file in junit? How can I access that class for testing?

In a software for mutation testing, a lot of mutants of java extension files (like mutant01.java) are created. 在用于突变测试的软件中,创建了许多Java扩展文件的突变体(例如mutant01.java)。 Now I need to test these files by using jUnit4. 现在,我需要使用jUnit4测试这些文件。 I'm trying to find out the way that I will be able to read the file and then access a specific class from that file, and perform jUnit testing on it. 我试图找出一种方法,使我能够读取文件,然后从该文件访问特定的类,并对它执行jUnit测试。 But I need help to do it? 但是我需要帮助吗?

I had found the ways that only results that my file is uploaded but I'm not be able to access the contents or specific class from that file. 我已经找到了仅导致文件上传的方法,但是无法访问该文件的内容或特定类。

@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());

I'm expecting that I become able to access the class from a java extension file and then perform junit testing on it but actually I'm stuck on it. 我期望我能够从Java扩展文件访问该类,然后对其执行junit测试,但实际上我被卡住了。

AS @John Mercier pointed you must compile your class first and then load it. AS @John Mercier指出您必须先编译您的类,然后再加载它。 You could use jOOR in order to do it easier. 您可以使用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. jOOR-Java中的Fluent反射jOOR是一个非常简单的Fluent API,它以更直观的方式提供对Java类结构的访问。 The JDK's reflection APIs are hard and verbose to use. JDK的反射API很难使用且冗长。 Other languages have much simpler constructs to access type meta information at runtime. 其他语言具有更简单的构造,可以在运行时访问类型元信息。 Let us make Java reflection better. 让我们使Java反射更好。

For use with Java 9+ 适用于Java 9+

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

For use with Java 8+ 适用于Java 8+

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

For use with Java 6+ 适用于Java 6+

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

Usage example: 用法示例:

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());

Note you must read your .java file before as a String 请注意,您必须先将.java文件读为字符串

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM