E
E
Erimax2022-03-07 10:17:26
symfony
Erimax, 2022-03-07 10:17:26

How to put class instance in mock tests?

Hello. There is a test code.

How to make it return 5 in mock? In Laravel I did it like this https://laravel.com/docs/9.x/mocking#mocking-objects Is there such a thing in symfony? I need a mock instance weight when this class is called with this method in other places, what is the best mock?

Example here https://stackoverflow.com/questions/61596662/symfo... Required
for api test

<?php

namespace App\Tests;

use App\Service\DaDataService;
use PHPUnit\Framework\TestCase;
use Mockery;

class DaDataTest extends TestCase
{
    public function testSomething(): void
    {
        $mock = Mockery::mock(DaDataService::class);

        $mock->shouldReceive('getDaData')
            ->zeroOrMoreTimes()
            ->andReturn(5);

        $daData = new DaDataService();
        $test = $daData->getDaData();
    }
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
E
Erimax, 2022-03-07
@Erimax

Decided so
6225ff31923f4867639853.png

<?php

namespace App\Tests;

use ApiPlatform\Core\Bridge\Symfony\Bundle\Test\ApiTestCase;
use App\Service\DaDataService;
use Mockery;

class ApiTest extends ApiTestCase
{
    public function testDaDataRequest(): void
    {
        $client = static::createClient();
/*        $mock = $this->getMockBuilder(DaDataService::class)
            ->disableOriginalConstructor()
            ->getMock();

        $mock->expects($this->once())
            ->method('getDaData')
            ->willReturn(20);*/

        $mock = Mockery::mock(DaDataService::class);

        $mock->shouldReceive('getDaData')
            ->zeroOrMoreTimes()
            ->andReturn(7);

        $client->getContainer()->set(DaDataService::class, $mock);
        $response = $client->request('GET', '/test');

        $content = json_decode($response->getContent(), true);

        self::assertEquals(7, $content['returnTest']);
        self::assertResponseIsSuccessful();
    }
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question