sophie-spec / throws
验证可调用对象抛出的异常
0.1.4
2022-02-03 17:42 UTC
Requires
- php: >=7.4.0
Requires (Dev)
- consolidation/robo: ^2.0
- friendsofphp/php-cs-fixer: ^2.16
- mockery/mockery: ^1.3
- phlak/semver: ^3.0
- phpmd/phpmd: ^2.8
- phpro/grumphp: ^0.17.1
- povils/phpmnd: ^2.1
- sebastian/phpcpd: ^4.1
- sensiolabs/security-checker: ^6.0
- symfony/error-handler: ^5.0
- symfony/var-dumper: ^5.0
- vimeo/psalm: ^3.7
README
它是一个单元测试工具,用于验证可调用对象是否抛出(或不抛出)异常。
安装
composer require --dev sophie-spec/throws
需要 PHP >= 7.4。
使用
根据上下文,throws()
和 throws_not()
可以抛出 ShouldHaveThrownException
或 ShouldHaveNotThrownException
。
$legal_age = function ($age) { if ($age < 18) { throw new UnderLegalAgeException("Not a legal age"); } }; // It does not throw an exception since // $legal_age throws an exception, as expected. throws(fn() => $legal_age(5)); // Here, it throws a ShouldHaveThrownException. throws(fn() => $legal_age(20)); // We can specify what exception we're expecting: // since we tell to throws() to catch UnderLegalAgeException exceptions // it won't throw an exception itself. throws(fn() => $legal_age(5), UnderLegalAgeException::class); // Of course, we can tell it to catch Exception exceptions, // and it would catch UnderLegalAgeException as expected. throws(fn() => $legal_age(5), Exception::class); // Here, it would throw a ShouldHaveNotThrownException // because we're catching SomeOtherException and nothing more. throws(fn() => $legal_age(5), SomeOtherException::class); // And, of course, you can catch several exception types. throws( fn() => $legal_age(5), SomeOtherException::class, UnderLegalAgeException::class ); // Here's the opposite of throws(), in this example // it throws a ShouldHaveNotThrownException. throws_not(fn() => $legal_age(5)); // Yay! $legal_age(20) does not throw an exception! throws_not(fn() => $legal_age(20)); // Like throws(), we can specify some exception classes to not catch. // Here, $legal_age(5) still throws an exception and since we're just // verifying that it does not throw an InvalidArgumentException, so // throws_not() does not throw a ShouldHaveNotThrownException. throws_not(fn() => $legal_age(5), InvalidArgumentException::class); // Now, it throws a ShouldHaveNotThrownException. throws_not(fn() => $legal_age(5), UnderLegalAgeException::class);
请注意,这是非常重要的,throws_not()
可能会导致假阳性。当你试图捕获特定异常时,如果发生另一个异常,它将被忽略。因此,在使用 throws_not()
进行特定异常捕获时,请确保你了解自己在做什么!
许可证
MIT.