PHP code example of tweakers / symfony-service-mock

1. Go to this page and download the library: Download tweakers/symfony-service-mock 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/ */

    

tweakers / symfony-service-mock example snippets




namespace App;

class TestService
{
    private $stuff;

    public function getStuff()
    {
        return $this->stuff;
    }

    public function setStuff($stuff)
    {
        $this->stuff = $stuff;
    }
}



namespace App\Tests;

use App\TestService;
use Symfony\Bundle\FrameworkBundle\Test\KernelTestCase;

class TestServiceTest extends KernelTestCase
{
    protected function setUp()
    {
    	parent::setUp();

    	self::bootKernel();
    }

    protected function tearDown()
    {
        parent::tearDown();
        
        // Make sure the original version is restored inside the proxy
        self::$container->get(TestService::class)->restoreOriginalService();
    }

    public function testServiceBehaviorCanBeChanged(): void
    {
        // Set the value of "stuff" to 39 in the original TestService
        $service = self::$container->get(TestService::class);
        $service->setStuff(39);

        $this->assertSame(39, $service->getStuff());

        // Set our mock as alternative for this test
        $mock = $this->createMock(TestService::class);
        $mock->method('getStuff')->willReturn(42);
        
        $service->setAlternativeService($mock);

        $this->assertSame(42, $service->getStuff());
        
        // Revert to original service
        $service->restoreOriginalService();
        $this->assertSame(39, $service->getStuff());
    }
}