phrity / net-mock
phrity/net-stream 的模拟层
2.1.0
2024-09-14 12:10 UTC
Requires
- php: ^8.0
- phrity/net-stream: ^2.1
- phrity/net-uri: ^2.0
- psr/log: ^1.0 | ^2.0 | ^3.0
Requires (Dev)
- php-coveralls/php-coveralls: ^2.0
- phpunit/phpunit: ^9.0 | ^10.0 | ^11.0
- squizlabs/php_codesniffer: ^3.0
This package is auto-updated.
Last update: 2024-09-14 12:11:28 UTC
README
介绍
编写使用流进行测试的代码是有问题的。此库为 phrity/net-stream 提供了模拟层,允许开发者验证和模拟流交互。
安装
使用 Composer 进行安装;
composer require phrity/net-mock
使用方法
此库中的类与 net-stream 库中的类完全兼容。默认情况下,调用模拟类将传播到实际实现类。
use Phrity\Net\StreamFactory as RealStreamFactory; use Phrity\Net\Mock\StreamFactory as MockStreamFactory; // Your code should allow setting stream classes $my_stream_user = new StreamUsingClass(); $my_stream_user->setStreamfactory($mock ? new MockStreamFactory() : new RealStreamFactory()); $my_stream_user->run();
记录交互
通过添加一个兼容 PSR-3 的记录器,所有调用将被记录。该库包含一个简单的 EchoLogger,但任何兼容的记录器均可使用。
use Phrity\Net\Mock\EchoLogger; use Phrity\Net\Mock\Mock; use Phrity\Net\Mock\StreamFactory; Mock::setLogger(new EchoLogger()); $my_stream_user = new StreamUsingClass(); $my_stream_user->setStreamfactory(new StreamFactory()); $my_stream_user->run();
模拟交互
通过注册一个回调处理程序,所有调用将通过该回调进行。
use Phrity\Net\Mock\Mock; use Phrity\Net\Mock\StreamFactory; Mock::setCallback(function (int $counter, string $method, array $params, callable $default) { // Assert call and parameters // The returned value will be passed back to calling code. // If you want to return the result of original code, use the $default callable return $default(); }); $my_stream_user = new StreamUsingClass(); $my_stream_user->setStreamfactory(new StreamFactory()); $my_stream_user->run();