javacompiler-constructionjunit4plexus

Compiling a java class with plexus-compiler-eclipse and running it as a JUnit test


I am currently trying to generate code on the fly, compile it then run it as a JUnit4 test. I am quite close to the goal, but I have an issue which might be either with plexus-compiler-eclipse or how I load the compiled class. Let me explain:

  1. I write to a file the java code using a simple FileWriterWithEncoding
  2. I compile it as Java6 code (source-target-compliance) using plexus-compiler-eclipse (also tried with plexus-compiler-javac) using EclipseJavaCompiler().performCompile(CompilerConfiguration)
  3. I load the class using URLClassLoader.newInstance(new URL[] {resource }).loadClass("classname") where resource is getClass().getResource("filename") (also tried with getClass().forName(className, true, classLoader) where the classLoader is the same URLClassLoader as above)
  4. Then I use an instance of JUnitCore to run my generated test class using JUnitCore().run(result of loading the class above)

Everything seems fine until point 4, where JUnit does not see any test method on the class (I obviously did annotate with @org.junit.Test each test method in the generated code). Debugging, I can see that if I do a newInstance() on the loaded class or inspect the loaded class, I have no annotations, no public methods, no declared fields, SFA!!! The newInstance() only has a private member, which is normal, since its reference type is Object, but somehow I am not able to cast it to try calling the public methods that should be there.

Any idea what I am missing in my compilation/class loading that makes the runtime class incomplete?

Thanks in advance for any ideas...


Solution

  • Apparently, this was pretty simple! I found this answer that made me aware that my URLClassLoader was missing a parent.