0

In a software for mutation testing, a lot of mutants of java extension files (like mutant01.java) are created. Now I need to test these files by using 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. 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.

dr.faisu
  • 1
  • 1
  • 1
    Hello. The java file needs to be compiled before you will be able to use the class. To get help we will need more info. What build tool are you using to generate the classes and run the tests? There are many examples of generating code and using the classes in tests for gradle and maven. – John Mercier Aug 01 '19 at 19:28

1 Answers1

0

AS @John Mercier pointed you must compile your class first and then load it. You could use jOOR in order to do it easier.

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.

For use with Java 9+

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

For use with Java 8+

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

For use with 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

eHayik
  • 2,981
  • 1
  • 21
  • 33