1 30 package org.apache.commons.httpclient; 31 32 import java.io.ByteArrayOutputStream ; 33 import java.io.IOException ; 34 import java.io.PrintStream ; 35 import java.io.PrintWriter ; 36 import java.io.StringWriter ; 37 38 import junit.framework.Test; 39 import junit.framework.TestCase; 40 import junit.framework.TestSuite; 41 42 46 public class TestExceptions extends TestCase 47 { 48 49 public TestExceptions(String testName) { 51 super(testName); 52 } 53 54 public static void main(String args[]) { 56 String [] testCaseName = { TestExceptions.class.getName() }; 57 junit.textui.TestRunner.main(testCaseName); 58 } 59 60 62 public static Test suite() { 63 return new TestSuite(TestExceptions.class); 64 } 65 66 67 public void testGetCause() { 68 69 Exception aCause = new IOException ("the cause"); 70 71 try { 72 throw new HttpException("http exception", aCause); 73 } 74 catch (HttpException e) { 75 assertEquals("Retrieve cause from caught exception", e.getCause(), aCause); 76 } 77 } 78 79 80 public void testStackTraceWriter() { 81 82 Exception aCause = new IOException ("initial exception"); 83 try { 84 throw new HttpException("http exception", aCause); 85 } 86 catch (HttpException e) { 87 StringWriter stringWriter = new StringWriter (); 89 PrintWriter writer = new PrintWriter (stringWriter); 90 e.printStackTrace(writer); 91 writer.flush(); 92 String stackTrace = stringWriter.toString(); 93 94 validateStackTrace(e, stackTrace); 96 } 97 } 98 99 100 public void testStackTraceStream() { 101 102 Exception aCause = new IOException ("initial exception"); 103 try { 104 throw new HttpException("http exception", aCause); 105 } 106 catch (HttpException e) { 107 ByteArrayOutputStream byteStream = new ByteArrayOutputStream (); 109 PrintStream stream = new PrintStream (byteStream); 110 e.printStackTrace(stream); 111 stream.flush(); 112 String stackTrace = byteStream.toString(); 114 validateStackTrace(e, stackTrace); 116 } 117 } 118 119 123 private void validateStackTrace(HttpException exception, String stackTrace) { 124 assertTrue("Starts with exception string", stackTrace.startsWith(exception.toString())); 125 126 Throwable cause = exception.getCause(); 127 if (cause != null) { 128 assertTrue("Contains 'cause'", stackTrace.toLowerCase().indexOf("cause") != -1); 129 assertTrue("Contains cause.toString()", stackTrace.indexOf(cause.toString()) != -1); 130 } 131 } 132 } 133 | Popular Tags |