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 package org.apache.commons.httpclient;
30
31 import java.io.ByteArrayOutputStream;
32 import java.io.IOException;
33 import java.io.PrintStream;
34 import java.io.PrintWriter;
35 import java.io.StringWriter;
36
37 import junit.framework.Test;
38 import junit.framework.TestCase;
39 import junit.framework.TestSuite;
40
41 /***
42 *
43 * @author <a href="mailto:laura@lwerner.org">Laura Werner</a>
44 */
45 public class TestExceptions extends TestCase
46 {
47
48
49 public TestExceptions(String testName) {
50 super(testName);
51 }
52
53
54 public static void main(String args[]) {
55 String[] testCaseName = { TestExceptions.class.getName() };
56 junit.textui.TestRunner.main(testCaseName);
57 }
58
59
60
61 public static Test suite() {
62 return new TestSuite(TestExceptions.class);
63 }
64
65 /*** Make sure that you can retrieve the "cause" from an HttpException */
66 public void testGetCause() {
67
68 Exception aCause = new IOException("the cause");
69
70 try {
71 throw new HttpException("http exception", aCause);
72 }
73 catch (HttpException e) {
74 assertEquals("Retrieve cause from caught exception", e.getCause(), aCause);
75 }
76 }
77
78 /*** Make sure HttpConnection prints its stack trace to a PrintWriter properly */
79 public void testStackTraceWriter() {
80
81 Exception aCause = new IOException("initial exception");
82 try {
83 throw new HttpException("http exception", aCause);
84 }
85 catch (HttpException e) {
86
87 StringWriter stringWriter = new StringWriter();
88 PrintWriter writer = new PrintWriter(stringWriter);
89 e.printStackTrace(writer);
90 writer.flush();
91 String stackTrace = stringWriter.toString();
92
93
94 validateStackTrace(e, stackTrace);
95 }
96 }
97
98 /*** Make sure HttpConnection prints its stack trace to a PrintStream properly */
99 public void testStackTraceStream() {
100
101 Exception aCause = new IOException("initial exception");
102 try {
103 throw new HttpException("http exception", aCause);
104 }
105 catch (HttpException e) {
106
107 ByteArrayOutputStream byteStream = new ByteArrayOutputStream();
108 PrintStream stream = new PrintStream(byteStream);
109 e.printStackTrace(stream);
110 stream.flush();
111 String stackTrace = byteStream.toString();
112
113
114 validateStackTrace(e, stackTrace);
115 }
116 }
117
118 /***
119 * Make sure an HttpException stack trace has the right info in it.
120 * This doesn't bother parsing the whole thing, just does some sanity checks.
121 */
122 private void validateStackTrace(HttpException exception, String stackTrace) {
123 assertTrue("Starts with exception string", stackTrace.startsWith(exception.toString()));
124
125 Throwable cause = exception.getCause();
126 if (cause != null) {
127 assertTrue("Contains 'cause'", stackTrace.toLowerCase().indexOf("cause") != -1);
128 assertTrue("Contains cause.toString()", stackTrace.indexOf(cause.toString()) != -1);
129 }
130 }
131 }