Here's what I've been using myself in my JUnit tests for a while, which is
quite similar to the proposed feature, in addition to having the same name
;-)
/**
* Ensures a code block always throws a specific exception type.
* <p>
* The following code:
* <pre>
* assertThrows(new NullPointerException(), new T() { public void f() {
* String s = null; s.length();
* }});
* </pre>
* is functionaly equivalent to the traditional code below,
* while being more explicit and more compact:
* <pre>
* try {
* String s = null; s.length();
* fail("Should have raise: "+NullPointerException.class.getName());
* }
* catch (NullPointerException e) {
* // DO NOTHING. Expected exception was thrown!
* }
* catch (Throwable t) {
* fail("Should have raise: "+NullPointerException.class.getName()
* +"\nbut instead raised: "+t);
* }
* </pre>
* When testing a method or code block that throws checked exceptions
* (Exception classes not deriving from RuntimeException), one must
* implement the <code>e()</code> method of class <code>T</code> instead
* of method <code>f()</code>, as it declares to throw the checked
* exception. Here is such an example:
* <pre>
* assertThrows(new IOException("bad encoding"),
* new T() { public void e() throws Exception {
* String s = "The quick brown fox jumps over the lazy dog";
* byte[] bytes = s.getBytes("non-existant-encoding");
* }});
* </pre>
* <em>Note that any message passed to the constructor of the
* <code>expected</code> exception (as illustrated by the code snippet
* above) will be displayed if it is not thrown as expected!</em>
*
* @param expected the exception class expected to be thrown.
* @param t the <em>runnable</em> to execute. We use f, since
* it allows a more compact notation than java.lang.Runnable.
*
* @throws AssertionFailedError if either f() or e() does not throw
* the expected exception.
*/
public void assertThrows(Throwable expected, T t) {
try {
t.f();
t.e();
fail("Should have raised: "+expected);
}
catch (Throwable e) {
if (!(expected.getClass().isInstance(e))) {
fail("Should have raised: "+expected+"\nbut raised instead: "+e);
}
}
}
--DD
-----Original Message-----
From: Wannheden, Knut [mailto:[EMAIL PROTECTED]]
Sent: Thursday, November 28, 2002 5:21 AM
To: 'Jakarta Commons Users List'
Subject: RE: [jelly] unit testing: detecting exceptions
Good suggestions. I have sent a patch to the dev list now which includes
the <test:assertThrown/> tag as you describe it. I was thinking if not
maybe the name should be <test:assertThrows/> instead?
--
To unsubscribe, e-mail: <mailto:[EMAIL PROTECTED]>
For additional commands, e-mail: <mailto:[EMAIL PROTECTED]>