forked from Codeception/AssertThrows
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathAssertThrows.php
79 lines (65 loc) · 2.16 KB
/
AssertThrows.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
<?php
namespace Codeception;
use PHPUnit\Framework\AssertionFailedError;
use PHPUnit\Framework\TestCase;
trait AssertThrows
{
/**
* Asserts that callback throws an exception
*
* @param $throws
* @param callable $fn
* @throws \Exception
*/
public function assertThrows($throws, callable $fn)
{
$this->assertThrowsWithMessage($throws, false, $fn);
}
/**
* Asserts that callback throws an exception with a message
*
* @param $throws
* @param $message
* @param callable $fn
*/
public function assertThrowsWithMessage($throws, $message, callable $fn)
{
/** @var $this TestCase * */
$result = $this->getTestResultObject();
if (is_array($throws)) {
$message = ($throws[1]) ? $throws[1] : false;
$throws = $throws[0];
}
if (is_string($message)) {
$message = strtolower($message);
}
try {
call_user_func($fn);
} catch (AssertionFailedError $e) {
if ($throws !== get_class($e)) {
throw $e;
}
if ($message !== false && $message !== strtolower($e->getMessage())) {
throw new AssertionFailedError("exception message '$message' was expected, but '" . $e->getMessage() . "' was received");
}
} catch (\Exception $e) {
if ($throws) {
if ($throws !== get_class($e)) {
throw new AssertionFailedError("exception '$throws' was expected, but " . get_class($e) . ' was thrown');
}
if ($message !== false && $message !== strtolower($e->getMessage())) {
throw new AssertionFailedError("exception message '$message' was expected, but '" . $e->getMessage() . "' was received");
}
} else {
throw $e;
}
}
if ($throws) {
if (isset($e)) {
$this->assertTrue(true, 'exception handled');
} else {
throw new AssertionFailedError("exception '$throws' was not thrown as expected");
}
}
}
}