PHP code example of proklung / phpunit-testing-tools
1. Go to this page and download the library: Download proklung/phpunit-testing-tools 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/ */
proklung / phpunit-testing-tools example snippets
use Prokl\TestingTools\Base\BaseTestCase;
use Prokl\TestingTools\Tools\Container\BuildContainer;
class ContainerAwareBaseTestCase extends BaseTestCase
{
/**
* @inheritDoc
* @throws Exception
*/
protected function setUp(): void
{
$this->container = static::$testContainer = BuildContainer::getTestContainer(
[
'dev/test_container.yaml',
'dev/local.yaml'
],
'/Resources/config',
[new SampleCompilerPass()], // Опциональный параметр - кастомные compiler passes,
'dev', // Окружение. По умолчанию - dev
true // Debug. По умолчанию - true,
['service_to_mock'] // Сервисы, подлежащие мокингу (см. подраздел Моки сервисов)
);
parent::setUp();
}
}
use Prokl\TestingTools\Tools\ServiceMocker;
use Prokl\TestingTools\Base\BaseTestCase;
class MyTest extends BaseTestCase
{
use RestoreServiceContainer;
protected function setUp(): void
{
parent::setUp();
$this->container = BuildContainer::getTestContainer(
[
'test_container.yaml'
],
'/../../../../tests/Standalone/Resource/config',
[],
'dev',
true,
['filesystem.local.adapter'] // Сервис, который будет заменен моком.
);
}
public function testFoo()
{
// For all calls
ServiceMock::all($this->container->get('filesystem.local.adapter'), 'getAdapter', function () {
return new Local(
$_SERVER['DOCUMENT_ROOT'] . '/test/');
});
$result = $this->container->get('filesystem.local.adapter');
// For only the next call
ServiceMock::next($this->container->get('filesystem.local.adapter'), 'getAdapter', function () {
return new Local(
$_SERVER['DOCUMENT_ROOT'] . '/test/');
});
// This will queue a new callable
ServiceMock::next($this->container->get('filesystem.local.adapter'), 'getAdapter', function () {
throw new \InvalidArgument('getAdapter can call once time!');
});
$mock = // create a PHPUnit mock or any other mock you want.
ServiceMocker::swap($this->container->get('filesystem.local.adapter'), $mock);
// ...
$service = $this->container->get('filesystem.local.adapter');
$result = $service->getAdapter(); // Метод сервиса (или сервис целиком) подменен.
}
protected function tearDown(): void
{
// To make sure we don't affect other tests
ServiceMock::resetAll();
// You can
use Prokl\TestingTools\Traits\BootTestKernelTrait;
class ExampleTest extends \Prokl\TestingTools\Base\BaseTestCase
{
use BootTestKernelTrait;
protected function setUp(): void
{
parent::setUp();
$container = new ContainerBuilder();
// ... Наполнение тестового контейнера.
self::$kernel = $this->bootTestKernel($container);
}
}
// Замокается полностью (т.е. не важно с какими параметрами пройдет вызов) функция in_the_loop
$this->mockerFunctions->setNamespace('\Tests\API')
->full('in_the_loop', true)
->mock();
use App\Command\CreateUserCommand;
use Prokl\TestingTools\Base\BaseTestCase;
use Prokl\TestingTools\Tools\Console\InteractsWithConsole;
use Prokl\TestingTools\Traits\BootTestKernelTrait;
class CreateUserCommandTest extends BaseTestCase
{
use InteractsWithConsole;
use BootTestKernelTrait;
protected function setUp(): void
{
parent::setUp();
$container = new ContainerBuilder();
$container->setDefinition(
IntegrityCheck::class,
new Definition(IntegrityCheck::class, [])
)->setTags(['console.command' => ['command' => 'module:еуые']])->setPublic(true);
self::$kernel = $this->bootTestKernel($container);
$this->cliApplication = new \Symfony\Bundle\FrameworkBundle\Console\Application(self::$kernel);
$this->cliApplication->add($container->get(IntegrityCheck::class));
}
public function test_can_create_user(): void
{
$this->executeConsoleCommand('create:user kbond --admin --role=ROLE_EMPLOYEE --role=ROLE_MANAGER')
->assertSuccessful() // command exit code is 0
->assertOutputContains('Creating admin user "kbond"')
->assertOutputContains('with roles: ROLE_EMPLOYEE, ROLE_MANAGER')
->assertOutputNotContains('regular user')
;
// advanced usage
$this->consoleCommand(CreateUserCommand::class) // can use the command class or "name"
->splitOutputStreams() // by default stdout/stderr are combined, this options splits them
->addArgument('kbond')
->addOption('--admin') // with or without "--" prefix
->addOption('role', ['ROLE_EMPLOYEE', 'ROLE_MANAGER'])
->addOption('-R') // shortcut options
use App\Command\CreateUserCommand;
use PHPUnit\Framework\TestCase;
use Prokl\TestingTools\Tools\Console\TestCommand;
class CreateUserCommandTest extends TestCase
{
public function test_can_create_user(): void
{
TestCommand::for(new CreateUserCommand(/** args... */))
->splitOutputStreams() // by default stdout/stderr are combined, this options splits them
->addArgument('kbond')
->addOption('--admin') // with or without "--" prefix
->addOption('role', ['ROLE_EMPLOYEE', 'ROLE_MANAGER'])
->addOption('-R') // shortcut options n conjunction with ->splitOutputStreams()
->dump() // dump() the status code/outputs and continue
->dd() // dd() the status code/outputs
;
// testing interactive commands
TestCommand::for(new CreateUserCommand(/** args... */))
->addInput('kbond')
->addOption('--no-interaction') // commands are run interactively if input is provided, use this option to disable
->execute()
->assertSuccessful()
->assertOutputContains('Creating regular user "kbond"')
;
// access result
$result = TestCommand::for(new CreateUserCommand(/** args... */))->execute();
$result->statusCode();
$result->output();
$result->errorOutput();
}
}
class MyClass
{
private string $privateProperty = 'private value';
private function privateMethod(): string
{
return 'private return value';
}
}
$myClass = new Myclass();