1 16 17 package org.springframework.test; 18 19 import junit.framework.Assert; 20 import junit.framework.AssertionFailedError; 21 22 95 public abstract class AssertThrows { 96 97 private Class expectedException; 98 99 private String failureMessage; 100 101 102 109 public AssertThrows(Class expectedException) { 110 this(expectedException, null); 111 } 112 113 122 public AssertThrows(Class expectedException, String failureMessage) { 123 if (expectedException == null) { 124 throw new IllegalArgumentException ("The 'expectedException' argument is required"); 125 } 126 if (!Exception .class.isAssignableFrom(expectedException)) { 127 throw new IllegalArgumentException ( 128 "The 'expectedException' argument is not an Exception type (it obviously must be)"); 129 } 130 this.expectedException = expectedException; 131 this.failureMessage = failureMessage; 132 } 133 134 135 139 protected Class getExpectedException() { 140 return this.expectedException; 141 } 142 143 147 public void setFailureMessage(String failureMessage) { 148 this.failureMessage = failureMessage; 149 } 150 151 155 protected String getFailureMessage() { 156 return this.failureMessage; 157 } 158 159 160 165 public abstract void test() throws Exception ; 166 167 168 177 public void runTest() { 178 try { 179 test(); 180 doFail(); 181 } 182 catch (Exception actualException) { 183 checkExceptionExpectations(actualException); 184 } 185 } 186 187 197 protected void doFail() { 198 Assert.fail(createMessageForNoExceptionThrown()); 199 } 200 201 207 protected String createMessageForNoExceptionThrown() { 208 StringBuffer sb = new StringBuffer (); 209 sb.append("Should have thrown a [").append(this.getExpectedException()).append("]"); 210 if (getFailureMessage() != null) { 211 sb.append(": ").append(getFailureMessage()); 212 } 213 return sb.toString(); 214 } 215 216 226 protected void checkExceptionExpectations(Exception actualException) { 227 if (!getExpectedException().isAssignableFrom(actualException.getClass())) { 228 AssertionFailedError error = 229 new AssertionFailedError(createMessageForWrongThrownExceptionType(actualException)); 230 error.initCause(actualException); 231 throw error; 232 } 233 } 234 235 239 protected String createMessageForWrongThrownExceptionType(Exception actualException) { 240 StringBuffer sb = new StringBuffer (); 241 sb.append("Was expecting a [").append(getExpectedException().getName()); 242 sb.append("] to be thrown, but instead a [").append(actualException.getClass().getName()); 243 sb.append("] was thrown."); 244 return sb.toString(); 245 } 246 247 } 248 | Popular Tags |