matthiasnoback / phpunit-asynchronicity
用于断言与PHPUnit异步发生的库
v3.0.1
2024-02-07 08:43 UTC
Requires
- php: ^8.1
Requires (Dev)
- ext-pcntl: *
- phpstan/phpstan: ^1.10
- phpunit/phpunit: ^10.0 || ^11.0
This package is auto-updated.
Last update: 2024-09-07 09:46:29 UTC
README
使用此库,您可以使测试等待某些条件,例如测试另一个进程的输出。
请参阅我关于此主题的博客文章,其中解释了概念并提供了一些代码示例。请注意,该文章涵盖了库的第1版。
用法
使用PHPUnit
use Asynchronicity\PHPUnit\Asynchronicity; use PHPUnit\Framework\Assert; use PHPUnit\Framework\TestCase; final class ProcessTest extends TestCase { use Asynchronicity; /** * @test */ public function it_creates_a_pid_file(): void { // start the asynchronous process that will eventually create a PID file... self::assertEventually( function (): void { Assert::assertFileExists(__DIR__ . '/pid'); } ); } }
使用Behat
在Behat的FeatureContext
中,您可以使用它,例如,一个页面最终包含某些文本。
use Asynchronicity\PHPUnit\Asynchronicity; use Behat\MinkExtension\Context\MinkContext; use PHPUnit\Framework\Assert; final class FeatureContext extends MinkContext { use Asynchronicity; /** * @Then the stock level has been updated to :expectedStockLevel */ public function thenTheFileHasBeenCreated(string $expectedStockLevel): void { self::assertEventually(function () use ($expectedStockLevel): void { $this->visit('/stock-levels'); $actualStockLevel = $this->getSession()->getPage())->find('css', '.stock-level')->getText(); Assert::assertEquals($expectedStockLevel, $actualStockLevel); }); } }
评论和建议
- 您可以在这些可调用函数内部使用
$this
。 - 您可以使用
use ($...)
来传递额外数据。 - 您可以在可调用函数内部抛出任何类型的异常,以表示您正在寻找的情况尚未发生。
- 通常,在可调用函数内部使用常规断言方法(PHPUnit或其他)会很方便。它们通常会提供足够详细的错误信息。
assertEventually()
支持额外的参数来设置超时和等待时间(以毫秒为单位)。- 您可以将任何可调用作为
assertEventually()
的第一个参数使用,包括具有__invoke()
方法的对象或类似[$object, 'methodName']
的东西。