jeudi 7 novembre 2019

Error while executing dynamically created JUnit Tests

I am trying to invoke a dynamically created Junit test class using the code below

    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    URL classUrl = javaClass.getParent().toFile().toURI().toURL();
    URLClassLoader classLoader = URLClassLoader.newInstance(new URL[] { classUrl });
    Class<?> clazz = Class.forName(fileName, true, classLoader);
    Object obj = clazz.newInstance();
    context.getLogger().log("Test Class Loader==>"+obj.getClass().getClassLoader()+"\n");
    JUnitCore junit = new JUnitCore();
    context.getLogger().log("JUnitCore Class Loader==>"+junit.getClass().getClassLoader()+"\n");
    junit.addListener(new TextListener(new PrintStream(outputStream)));
    Result result = junit.run(clazz);       
    return outputStream.toString();

Dynamically created test file

public class SampleJavaFileTest {
  String EXPECTED_OUTPUT_STRING="r3plac3";

  @Test
  public void testReplaceString() {
    SampleJavaFile sample = new SampleJavaFile();

    String outputString = sample.replaceString("replace","e","3");
    Assert.assertEquals(EXPECTED_OUTPUT_STRING, outputString);
 }
}

But I get the error as

There was 1 failure:
1) initializationError(JUnitTest)
org.junit.runners.model.InvalidTestClassError: Invalid test class 'JUnitTest':
1. No runnable methods
at org.junit.runners.ParentRunner.validate(ParentRunner.java:511)
at org.junit.runners.ParentRunner.<init>(ParentRunner.java:101)
at org.junit.runners.BlockJUnit4ClassRunner.<init>(BlockJUnit4ClassRunner.java:84)
at org.junit.runners.JUnit4.<init>(JUnit4.java:23)
at org.junit.internal.builders.JUnit4Builder.runnerForClass(JUnit4Builder.java:10)
at org.junit.runners.model.RunnerBuilder.safeRunnerForClass(RunnerBuilder.java:70)
at org.junit.internal.builders.AllDefaultPossibilitiesBuilder
  .runnerForClass(AllDefaultPossibilitiesBuilder.java:37)
at org.junit.runner.Computer.getRunner(Computer.java:50)
at org.junit.runner.Computer$1.runnerForClass(Computer.java:31)
at org.junit.runners.model.RunnerBuilder.safeRunnerForClass(RunnerBuilder.java:70)
at org.junit.runners.model.RunnerBuilder.runners(RunnerBuilder.java:125)
at org.junit.runners.model.RunnerBuilder.runners(RunnerBuilder.java:111)
at org.junit.runners.Suite.<init>(Suite.java:81)
at org.junit.runner.Computer$2.<init>(Computer.java:33)

I tried printing the class loaders of the dynamically created class and the JUnitCore class the results are

   Test Class Loader==>java.net.FactoryURLClassLoader@86be70a
   JUnitCore Class Loader==>java.net.URLClassLoader@49c2faae 

Upon going through various posts the answers provided are to use custom class loaders to resolve this issue. Can you assist on how to create a custom class loader to resolve this issue?

If not custom class loaders , how else can this be resolved?

Thanks!





Aucun commentaire:

Enregistrer un commentaire