ray / test-double
一个基于AOP的测试替身库
0.1.0
2022-10-04 07:59 UTC
Requires (Dev)
- doctrine/coding-standard: ^10.0
- phpmd/phpmd: ^2.13
- phpstan/phpstan: ^1.8
- phpunit/phpunit: ^9.5
- psalm/plugin-phpunit: ^0.17.0
- squizlabs/php_codesniffer: ^3.7
- vimeo/psalm: ^4.27
README
PHP的基于AOP的测试替身库
安装
Composer install
$ composer require ray/test-double --dev
什么是Spy(间谍)?
Spy是一种测试替身,它可以记录对它的每一次调用,并在事后验证某些交互是否发生。
创建Spy
您可以直接使用newInstance
或者通过绑定来指定。
通过newInstance()
$spyLog = new SpyLog(); $spy = (new Spy())->newInstance(Foo::class, 'add', $spyLog); // $spy records the 'add' method call
通过SpyModule
通过接口或类名指定要监视的目标。
$injector = new Injector(new class extends AbstractModule{ protected function configure(): void { $spyTargets = [ FooInterface::class, ]; $this->install(new SpyModule($spyTargets)); } } ); $spy = $injector->getInstance(Foo::class);
通过匹配器
使用Ray.Aop匹配器指定监视目标。
$injector = new Injector(new class extends AbstractModule { protected function configure(): void { $this->install(new SpyBaseModule()); $this->bindInterceptor( $this->matcher->any(), // any class $this->matcher->startsWith('add'), // methods startWith 'add' [SpyInterceptor::class] ); } }); $fake = $injector->getInstance(FakeAdd::class); $spy = $injector->getInstance(Foo::class);
断言
使用SpyLog::get($className, $methodName)
获取日志并进行断言。
public function testSpy() { $result = $foo->add(1, 2); // 3 $spy = $injector->getInstance(Spy::class); // @var array<int, Log> $addLog $addLog = $spyLog->getLogs(FakeAdd::class, 'add'); $subLog = $spyLog->getLogs(FakeAdd::class, 'sub'); $this->assertSame(1, count($addLog), 'Should have received once'); $this->assertSame(0, count($subLog), 'Should have not received'); $this->assertSame([1, 2], $addLog[0]->arguments); $this->assertSame(1, $addLog[0]->namedArguments['a']); }