PHP code example of ray / test-double

1. Go to this page and download the library: Download ray/test-double library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

ray / test-double example snippets


$spyLog = new SpyLog();
$spy = (new Spy())->newInstance(Foo::class, 'add', $spyLog);
// $spy records the 'add' method call

$injector = new Injector(new class extends AbstractModule{
        protected function configure(): void
        {
            $spyTargets = [
                FooInterface::class,
            ];
            $this->install(new SpyModule($spyTargets));
        }
    }
);
$spy = $injector->getInstance(Foo::class);

$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);

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']);

}