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 package org.codehaus.groovy.syntax.parser;
37
38 import groovy.lang.GroovyObject;
39 import groovy.lang.MissingClassException;
40 import groovy.lang.MissingPropertyException;
41
42 import java.io.ByteArrayInputStream;
43
44 import org.codehaus.groovy.classgen.TestSupport;
45 import org.codehaus.groovy.control.CompilationFailedException;
46
47 /***
48 * @author <a href="mailto:james@coredevelopers.net">James Strachan</a>
49 * @version $Revision: 1.5 $
50 */
51 public class CompilerErrorTest extends TestSupport {
52
53 public void testUnknownClassCatch() throws Exception {
54 MissingClassException e =
55 assertCompileFailed(
56 "class UnknownClass {\n"
57 + " main() {\n"
58 + " try {\n"
59 + " println('Hello World!')\n"
60 + " }\n"
61 + " catch (UnknownException e) {\n"
62 + " println('This will never happen')\n"
63 + " }\n"
64 + " }\n"
65 + "}\n");
66
67 assertEquals("UnknownException", e.getType());
68 }
69
70 public void testUnknownClassInNew() throws Exception {
71 MissingClassException e =
72 assertCompileFailed(
73 "class UnknownClass {\n" + " main() {\n" + " x = new UnknownThingy()\n" + " }\n" + "}\n");
74 assertEquals("UnknownThingy", e.getType());
75 }
76
77 public void testUnknownClassInAssignment() throws Exception {
78 GroovyObject object =
79 assertCompileWorks(
80 "class UnknownClass {\n" + " main() {\n" + " x = UnknownThingy\n" + " }\n" + "}\n");
81
82 try {
83 object.invokeMethod("main", null);
84 fail("Should have thrown exception due to unknown property");
85 }
86 catch (MissingPropertyException e) {
87 assertEquals("UnknownThingy", e.getProperty());
88 }
89
90
91
92
93 }
94
95 protected GroovyObject assertCompileWorks(String code) throws Exception {
96 Class type =
97 loader.parseClass(new ByteArrayInputStream(code.getBytes()), "ValidClass_" + getMethodName() + ".groovy");
98 return (GroovyObject) type.newInstance();
99 }
100
101 protected MissingClassException assertCompileFailed(String code) throws Exception {
102 try {
103 assertCompileWorks(code);
104
105 fail("Should have thrown an exception");
106 }
107 catch( CompilationFailedException e ) {
108 Exception cause = e.getUnit().getException(0);
109 if( cause instanceof MissingClassException ) {
110 System.out.println("Worked, threw: " + cause);
111
112 return (MissingClassException)cause;
113 }
114 throw e;
115 }
116 return null;
117 }
118
119 }