定制 sophie-spec/throws 二次开发

按需修改功能、优化性能、对接业务系统,提供一站式技术支持

邮箱:yvsm@zunyunkeji.com | QQ:316430983 | 微信:yvsm316

sophie-spec/throws

Composer 安装命令:

composer require sophie-spec/throws

包简介

Verify thrown exceptions from a callable

README 文档

README

It is a unit test tool to verify if a callable throws (or not) an exception.

Install

composer require --dev sophie-spec/throws

Requires PHP >= 7.4.

Use

Depending on the context, throws() and throws_not() can throw ShouldHaveThrownException or 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);

Please note, and it's very important, that throws_not() can lead to false positives. When you're trying to catch a specific exception, if another exception occurs it will be shut. Then, be sure to know what you're doing when using specific exceptions catching with throws_not()!

License

MIT.

统计信息

  • 总下载量: 23
  • 月度下载量: 0
  • 日度下载量: 0
  • 收藏数: 0
  • 点击次数: 0
  • 依赖项目数: 0
  • 推荐数: 0

GitHub 信息

  • Stars: 0
  • Watchers: 1
  • Forks: 0
  • 开发语言: PHP

其他信息

  • 授权协议: MIT
  • 更新时间: 2022-01-27

承接程序开发

PHP开发

VUE

Vue开发

前端开发

小程序开发

公众号开发

系统定制

数据库设计

云部署

网站建设

安全加固