PHP code example of ramunasd / symfony-container-mocks

1. Go to this page and download the library: Download ramunasd/symfony-container-mocks 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/ */

    

ramunasd / symfony-container-mocks example snippets




use Symfony\Component\HttpKernel\Kernel;
use Symfony\Component\Config\Loader\LoaderInterface;
use RDV\SymfonyContainerMocks\DependencyInjection\TestKernelTrait;

class AppKernel extends Kernel
{
    // use special container when env=test
    use TestKernelTrait;
    
    public function registerBundles()
    {
        return [
            // bundles
        ];
    }
    
    public function registerContainerConfiguration(LoaderInterface $loader)
    {
    }
}



namespace Acme\Bundle\AcmeBundle\Tests\Controller;

use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;
use Acme\Bundle\AcmeBundle\Service\Custom;

class AcmeControllerTest extends WebTestCase
{
    /**
     * @var \Symfony\Bundle\FrameworkBundle\Client $client
     */
    private $client;

    public function setUp()
    {
        parent::setUp();

        $this->client = static::createClient();
    }

    public function tearDown()
    {
        $this->client->getContainer()->tearDown();
        $this->client = null;

        parent::tearDown();
    }

    public function testSomethingWithMockedService()
    {
        $this->client->getContainer()->prophesize('acme.service.custom', Custom::class)
            ->someMethod([])
            ->willReturn(false)
            ->shouldBeCalledTimes(2);

        // ...
    }
}

$mock = $this->client->getContainer()->prophesize('acme.service.custom');
$mock
    ->myMethod()
    ->willReturn(true);

// create stub
$mock = $this->getMock(Custom::class);

// inject service mock
self::$kernel->getContainer()->setMock('acme.service.custom', $mock);

// reset container state
self::$kernel->getContainer()->unMock('acme.service.custom');


// set custom value during test
self::$kernel->getContainer()->setMockedParameter('acme.service.parameter1', 'customValue1');

// trigger service, assert results

// reset all parameters to original values
self::$kernel->getContainer()->clearMockedParameters();