From 5178719ac99d9f777e10cc0f95522113e2782902 Mon Sep 17 00:00:00 2001 From: Caleb Spare Date: Wed, 28 Mar 2012 21:32:50 -0700 Subject: [PATCH] Add assert.throwsException. --- shoulda.js | 22 +++++++++++++++++++++- 1 file changed, 21 insertions(+), 1 deletion(-) diff --git a/shoulda.js b/shoulda.js index 7f76e96..f5ae42d 100644 --- a/shoulda.js +++ b/shoulda.js @@ -61,6 +61,26 @@ var assert = { this.fail("Expected " + this._printObject(expected) + " but received " + this._printObject(actual)); }, + // It would be nice to call this 'throws', but all Java keywords are Javascript keywords and hence 'throws' + // is a JS keyword. Sigh. + throwsException: function(expression, expectedExceptionName) { + try { + expression(); + } catch(exception) { + if (expectedExceptionName) { + if (exception.name === expectedExceptionName) return; + else { + assert.fail("Expected exception " + expectedExceptionName + " to be thrown but exception " + + exception.name + " was thrown instead."); + } + } else return; + } + if (expectedExceptionName) + assert.fail("Expected exception " + expectedExceptionName + " but no exception was thrown."); + else + assert.fail("Expected exception but none was thrown."); + }, + fail: function(message) { throw new AssertionError(message); }, /* Used for printing the arguments passed to assertions. */ @@ -294,4 +314,4 @@ Stubs = { stubProperties.object[stubProperties.propertyName] = stubProperties.original; } } -}; \ No newline at end of file +};