forked from trung/InMemoryJavaCompiler
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathInMemoryJavaCompilerTest.java
More file actions
60 lines (48 loc) · 2.12 KB
/
InMemoryJavaCompilerTest.java
File metadata and controls
60 lines (48 loc) · 2.12 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
package org.mdkt.compiler;
import java.io.StringWriter;
import java.util.Map;
import org.junit.Assert;
import org.junit.Test;
/**
* Created by trung on 5/3/15.
*/
public class InMemoryJavaCompilerTest {
@Test
public void compile_whenTypical() throws Exception {
StringBuffer sourceCode = new StringBuffer();
sourceCode.append("package org.mdkt;\n");
sourceCode.append("public class HelloClass {\n");
sourceCode.append(" public String hello() { return \"hello\"; }");
sourceCode.append("}");
Class<?> helloClass = InMemoryJavaCompiler.compile("org.mdkt.HelloClass", sourceCode.toString());
Assert.assertNotNull(helloClass);
Assert.assertEquals(1, helloClass.getDeclaredMethods().length);
}
@Test
public void compile_severalFiles() throws Exception {
String cls1 = "public class A{ public B b() { return new B(); }}";
String cls2 = "public class B{ public String toString() { return \"B!\"; }}";
InMemoryJavaCompiler compiler = new InMemoryJavaCompiler();
compiler.addSource("A", cls1);
compiler.addSource("B", cls2);
Map<String,Class<?>> compiled = compiler.compileAll();
;
Assert.assertNotNull(compiled.get("A"));
Assert.assertNotNull(compiled.get("B"));
Class<?> aClass = compiled.get("A");
Object a = aClass.newInstance();
Assert.assertEquals("B!", aClass.getMethod("b").invoke(a).toString());
}
@Test
public void compile_filesWithInnerClasses() throws Exception {
StringBuffer sourceCode = new StringBuffer();
sourceCode.append("package org.mdkt;\n");
sourceCode.append("public class HelloClass {\n");
sourceCode.append(" private static class InnerHelloWorld { int inner; }\n");
sourceCode.append(" public String hello() { return \"hello\"; }");
sourceCode.append("}");
Class<?> helloClass = InMemoryJavaCompiler.compile("org.mdkt.HelloClass", sourceCode.toString());
Assert.assertNotNull(helloClass);
Assert.assertEquals(1, helloClass.getDeclaredMethods().length);
}
}