cornermonkey / phpunit-conditional-assertions
PHPUnit 测试用例扩展,允许执行条件断言。
0.1.0
2023-11-09 23:14 UTC
Requires
- php: ^8.0
- phpunit/phpunit: ^8.0 || ^9.0 || ^10.0
Requires (Dev)
- friendsofphp/php-cs-fixer: ^3.0
- phpstan/extension-installer: ^1.3
- phpstan/phpstan: ^1.10
- phpstan/phpstan-phpunit: ^1.3
- rector/rector: ^0.18.6
README
此库增加了对 PHPUnit 的任何现有断言进行条件调用的功能。此库的灵感来自 Pest 的条件期望以及希望在 PHPUnit 中实现类似功能。
作者和版权
Tim Lawson tim@lawson.fyi
此库采用 MIT 许可证。
安装
$ composer require --dev cornermonkey/phpunit-conditional-assertions
兼容性
此包与 PHP 8.0 及更高版本以及 PHPUnit 8.0 及更高版本兼容。
用法
只需在您的测试用例中使用 trait CornerMonkey\ConditionalAssertions\ConditionalAssertionTrait
。此 trait 为您的测试用例添加了 when
和 unless
方法。
示例
<?php use CornerMonkey\ConditionalAssertion\ConditionalAssertionTrait; use PHPUnit\Framework\TestCase; class MyTestCase extends TestCase { use ConditionalAssertionTrait; public function testConditionIsValid() { $this->when(true)->assertThat(true, true); $this->when(false)->assertThat(true, true); // This assertion will not be called $this->unless(true)->assertThat(true, true); // This assertion will not be called $this->unless(false)->assertThat(true, true); } }
您还可以将回调函数传递给 when
和 unless
方法。当条件为真时,将调用提供的回调。
<?php use CornerMonkey\ConditionalAssertion\ConditionalAssertionTrait; use PHPUnit\Framework\TestCase; class MyTestCase extends TestCase { use ConditionalAssertionTrait; public function dataProvider() { return [ [true], [false] ]; } /** * @dataProvider dataProvider */ public function testIfExceptionShouldBeThrown($shouldThrow) { $this->when($shouldThrow, function(TestCase $testCase, $value) { $testCase->expectException(Exception::class); }); if ($shouldThrow) { throw new Exception(); } } }