22
33import org .junit .jupiter .api .Assertions ;
44import org .junit .jupiter .api .Test ;
5+ import pl .mperor .lab .common .TestUtils ;
56
67import javax .script .ScriptEngine ;
78import javax .script .ScriptEngineManager ;
1112import java .awt .*;
1213import java .io .File ;
1314import java .io .IOException ;
15+ import java .lang .reflect .InvocationTargetException ;
16+ import java .net .MalformedURLException ;
17+ import java .net .URL ;
18+ import java .net .URLClassLoader ;
1419import java .nio .file .Files ;
1520
1621/**
@@ -32,24 +37,36 @@ public void testScriptingLanguageSupport() throws ScriptException {
3237 }
3338
3439 @ Test
35- public void testJavaDynamicCompilation () throws IOException {
36- File sourceFile = new File ("./ HelloWorld.java" );
40+ public void testJavaDynamicCompilation () throws IOException , ClassNotFoundException , InvocationTargetException , NoSuchMethodException , InstantiationException , IllegalAccessException {
41+ File sourceFile = new File ("HelloWorld.java" );
3742 String javaSourceCode = """
3843 public class HelloWorld {
39- public static void main(String[] args ) {
40- System.out.println ("Hello World!");
44+ public void sayHello( ) {
45+ System.out.print ("Hello World!");
4146 }
4247 }
4348 """ ;
4449 Files .write (sourceFile .toPath (), javaSourceCode .getBytes ());
4550
4651 JavaCompiler compiler = ToolProvider .getSystemJavaCompiler ();
4752 Assertions .assertNotNull (compiler , "JavaCompiler should not be null" );
48-
4953 int compilationResult = compiler .run (null , null , null , sourceFile .getAbsolutePath ());
5054 Assertions .assertEquals (0 , compilationResult , "Compilation should succeed with result 0!" );
55+ assertHelloWorldClassAccessible ();
56+
5157 Assertions .assertTrue (sourceFile .delete (), "Source file should be deleted after compilation" );
52- Assertions .assertTrue (new File ("./HelloWorld.class" ).delete (), "Now compilation result can be deleted!" );
58+ Assertions .assertTrue (new File ("HelloWorld.class" ).delete (), "Now compilation result can be deleted!" );
59+ }
60+
61+ private void assertHelloWorldClassAccessible () throws MalformedURLException , ClassNotFoundException , NoSuchMethodException , InvocationTargetException , InstantiationException , IllegalAccessException {
62+ URL [] urls = {new File ("" ).toURI ().toURL ()};
63+ URLClassLoader loader = new URLClassLoader (urls );
64+ Class <?> clazz = loader .loadClass ("HelloWorld" );
65+ Object instance = clazz .getDeclaredConstructor ().newInstance ();
66+ var readableOut = TestUtils .setTempSystemOut ();
67+ clazz .getDeclaredMethod ("sayHello" ).invoke (instance );
68+ Assertions .assertEquals (readableOut .all (), "Hello World!" );
69+ TestUtils .resetSystemOut ();
5370 }
5471
5572 @ Test
0 commit comments