Skip to content
Browse files

Merge pull request #6 from epixa/throws

Added test type for asserting a thrown exception
  • Loading branch information...
2 parents 2b8afe1 + d82860a commit 2d39b5b3db32abf97b8953daf6bc0beaf3c64493 @funkatron committed Oct 9, 2012
Showing with 42 additions and 0 deletions.
  1. +34 −0 FUnit.php
  2. +8 −0 example.php
View
34 FUnit.php
@@ -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
8 example.php
@@ -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 2d39b5b

Please sign in to comment.
Something went wrong with that request. Please try again.