1
2
3
4
5
6
7
8
9
10
11
12
13
14
15 package org.htmlunit;
16
17 import static org.junit.jupiter.api.Assertions.fail;
18
19 import java.io.PrintWriter;
20 import java.io.StringWriter;
21 import java.net.URL;
22
23 import org.htmlunit.html.HtmlPage;
24 import org.junit.jupiter.api.Test;
25
26
27
28
29
30
31
32 public final class ScriptExceptionTest extends SimpleWebTestCase {
33
34
35
36
37 @Test
38 public void constructor() throws Exception {
39 final String message = "bla bla";
40 final Throwable t = new RuntimeException(message);
41 final HtmlPage page = loadPage(DOCTYPE_HTML + "<html></html>");
42 final ScriptException exception = new ScriptException(page, t);
43
44 assertEquals(t, exception.getCause());
45 assertEquals(message, exception.getMessage());
46 }
47
48
49
50
51
52 @Test
53 public void getPage() throws Exception {
54 final String html = DOCTYPE_HTML + "<html><script>notExisting()</script></html>";
55 try {
56 loadPage(html);
57 }
58 catch (final ScriptException e) {
59 assertEquals(URL_FIRST, e.getPage().getUrl());
60 }
61 }
62
63
64
65
66
67
68
69
70
71 @Test
72 public void scriptStackTrace() throws Exception {
73 testScriptStackTrace("ScriptExceptionTest1");
74 testScriptStackTrace("ScriptExceptionTest2");
75 }
76
77 private void testScriptStackTrace(final String baseFileName) throws Exception {
78 try {
79 loadPage(getBrowserVersion(), getFileContent(baseFileName + ".html"), null,
80 new URL("http://www.gargoylesoftware.com/"));
81 }
82 catch (final ScriptException e) {
83 final StringWriter stringWriter = new StringWriter();
84 final PrintWriter printWriter = new PrintWriter(stringWriter);
85 e.printScriptStackTrace(printWriter);
86
87 final String expectedTrace = getFileContent(baseFileName + ".txt");
88 assertEquals(expectedTrace, stringWriter.toString());
89 return;
90 }
91 fail("Exception not thrown");
92 }
93
94
95
96
97 @Test
98 public void errorLineNumber() throws Exception {
99 testErrorLineNumber("testJsError1.html", 6);
100 testErrorLineNumber("testJsError2.html", 7);
101 testErrorLineNumber("testJsError3.html", 6);
102 testErrorLineNumber("testJsError4.html", 8);
103 }
104
105 private void testErrorLineNumber(final String fileName, final int errorLine) throws Exception {
106 final WebClient webClient = getWebClient();
107 final URL url = getClass().getClassLoader().getResource(fileName);
108 assertNotNull(url);
109 try {
110 final HtmlPage page = webClient.getPage(url);
111 page.getHtmlElementById("clickMe").click();
112 fail();
113 }
114 catch (final ScriptException e) {
115 assertEquals(errorLine, e.getFailingLineNumber());
116 }
117 }
118 }