Permalink
Browse files

Added test type for asserting a thrown exception

Sometimes it is useful to test functionality that throws known exceptions given
specific conditions. The only existing solution was to pass to ok() an anonymous
function that manually caught and verified the exception type.

This method is nicer.
  • Loading branch information...
1 parent 2b8afe1 commit d82860ab0b8fd5d61c31dbba5f0c6b0beae41650 @epixa epixa committed Oct 9, 2012
Showing with 42 additions and 0 deletions.
  1. +34 −0 FUnit.php
  2. +8 −0 example.php
View
@@ -637,6 +637,40 @@ public static function ok($a, $msg = null) {
}
/**
+ * assert that $callback throws an exception of type $exception
+ *
+ * If $params is an array, it is passed as arguments to the callback.
+ * Otherwise, it is assumed no arguments need to be passed.
+ *
+ * @param callable $callback Callback that should throw an exception
+ * @param array $params Callback that should throw an exception
+ * @param string $exception The exception class that should be thrown
+ * @param string $msg
+ * @return bool
+ */
+ public static function throws(callable $callback, $params, $exception = null, $msg = null) {
+ if (is_array($params)) {
+ $exception = $exception ?: 'Exception';
+ } else {
+ $msg = $exception;
+ $exception = $params;
+ $params = array();
+ }
+ try {
+ call_user_func_array($callback, $params);
+ $rs = false;
+ } catch (\Exception $e) {
+ $rs = $e instanceof $exception;
+ }
+ static::add_assertion_result(__FUNCTION__, array($callback, $exception), $rs, $msg);
+ if (!$rs) {
+ $txt = isset($e) ? 'got ' . get_class($e) : 'no exception thrown';
+ static::debug_out('Expected exception ' . $exception . ', but ' . $txt);
+ }
+ return $rs;
+ }
+
+ /**
* assert that $haystack has a key or property named $needle. If $haystack
* is neither, returns false
* @param string $needle the key or property to look for
View
@@ -34,6 +34,14 @@
fu::has('blam', $fooobj, "\$fooobj has a property named 'blam'");
});
+fu::test('Checking for exceptions', function() {
+ $callback = function() { throw new RuntimeException(); };
+ fu::throws($callback, 'RuntimeException', 'Correct exception');
+
+ $callback = function($foo) { throw new RuntimeException($foo); };
+ fu::throws($callback, array('bar'), 'LogicException', 'Not the correct exception');
+});
+
fu::test('Forced failure', function() {
fu::fail('This is a forced fail');
});

0 comments on commit d82860a

Please sign in to comment.