2

I am trying to build a Dynamic web project where user can practice Java code.

I got success on writing the code written by user in a .java file, compile the code & get error messages using Java Compile API.

Now, I need to run JUnit 1.4 Compatible test on that code.

I researched for it, and found something like parameterized junit testing. But my view on how should it be done isn't still clear.

UPDATE

This (http://codingbat.com/prob/p171896) is the exact thing what I'm trying to implement.

2
  • The first publicly-available version of JUnit was 3.7. Maybe you mean "JUnit4 Compatible", which was a big version change over the previous JUnit3, or "JUnit for Java 1.4", which this question defines nicely? Commented Sep 8, 2014 at 23:48
  • @JeffBowman thanx for noticing the question. Its actually "JUnit for Java 1.4". I know the JUnit testing, and had been using it for my projects. But in this project. I need to test the class file at runtime, which is written by the user. There comes my problem. Commented Sep 9, 2014 at 4:48

1 Answer 1

2

I solved this problem with the following steps:

  1. Compile the JUnit TestClass and the ClassToTest

    JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
    int compilerResult = compiler.run(null, null, null,"/path/to/TestClass.java", "/path/to/ClassToTest.java");
    System.out.println("Compiler result code: " + compilerResult);
    
  2. Load the compiled classes into the classloader

    File dir = new File("/path/to/class/files/");
    URL url = dir.toURI().toURL();
    URL[] urls = {url};
    ClassLoader classLoader = new URLClassLoader(urls);
    
  3. Run the tests (make sure that you add junit as a dependency of your project)

    Class<?> junitTest = Class.forName("TestClass", true, classLoader);
    Result result = junit.run(junitTest);
    

Edit: If you're not needing the JUnit tests to be dynamic you can skip the compilation of those tests and add them here: junit.run(JunitTest.class)

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.