1. Go to this page and download the library: Download net-tools/phpunit-given 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/ */
net-tools / phpunit-given example snippets
use olvlvl\Given\GivenTrait;
use PHPUnit\Framework\TestCase;
final class IntegerNameTest extends TestCase
{
use GivenTrait; // <-- adds the method 'given'
public function testName(): void
{
$mock = $this->createMock(IntegerName::class);
$mock->method('name')->will($this
->given(new Integer(6))->return("six")
->given(new Integer(12))->return("twelve")
->default()->throw(LogicException::class)
);
$this->assertEquals("six", $mock->name(new Integer(6)));
$this->assertEquals("twelve", $mock->name(new Integer(12)));
$this->expectException(LogicException::class);
$mock->name(new Integer(99));
}
}
$mock = $this->createMock(IntegerName::class);
$mock
->method('name')
->with(new Integer(6))
->willReturn("six");
$mock
->method('name')
->with(new Integer(12))
->willReturn("twelve");
// the next line crashes with: Expectation failed
$this->assertEquals("six", $mock->name(new Integer(6)));
$mock = $this->createMock(IntegerName::class);
$mock
->method('name')
->with(new Integer(6))->willReturn("six");
// the next line crashes with: Method parameters already configured
->with(new Integer(12))->willReturn("twelve");
$this->assertEquals("six", $mock->name(new Integer(6)));
$mock = $this->createMock(IntegerName::class);
$mock->method('name')->willReturnCallback(fn (Integer $int) => match ($int) {
new Integer(6) => 'six',
new Integer(12) => 'twelve',
default => throw new Exception
}));
$mock = $this->createMock(IntegerName::class);
$mock->method('name')->will($this->returnValueMap([
[ new Integer(6), "six" ],
[ new Integer(12), "twelve" ],
]));
$mock->name(new Integer(6)); // throws TypeError