Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unit testing Doctrine: can't mock repository method

I'm trying to mock a Doctrine repository and the entityManager, but PHPUnit keeps telling me that:

1) CommonUserTest::testGetUserById Trying to configure method "findBy" which cannot be configured because it does not exist, has not been specified, is final, or is static

Here's the snippet:

<?php
use \Domain\User as User;
use PHPUnit\Framework\TestCase;
use Doctrine\ORM\EntityRepository;
use Doctrine\ORM\EntityManager;

class CommonUserTest extends PHPUnit_Framework_TestCase
{    
    public function testGetUserById()
    {
        // mock the repository so it returns the mock of the user (just a random string)
        $repositoryMock = $this
            ->getMockBuilder(EntityRepository::class)
            ->disableOriginalConstructor()
            ->getMock();

        $repositoryMock->expects($this->any())
            ->method('findBy')
            ->willReturn('asdasd');

        // mock the EntityManager to return the mock of the repository
        $entityManager = $this
            ->getMockBuilder(EntityManager::class)
            ->disableOriginalConstructor()
            ->getMock();

        $entityManager->expects($this->any())
            ->method('getRepository')
            ->willReturn($repositoryMock);

        // test the user method
        $userRequest = new User($entityManager);
        $this->assertEquals('asdasd', $userRequest->getUserById(1));
    }
}

Any help? I tried a few variations of this code but can't get passed this specific error.

Thanks.

like image 310
afontcu Avatar asked Mar 07 '23 03:03

afontcu


1 Answers

Which version of PHPUnit are you using?

anyway, check this possible solution:

$repositoryMock = $this
            ->getMockBuilder(EntityRepository::class)
            ->setMethods(['findBy'])
            ->disableOriginalConstructor()
            ->getMock();

Should work.

like image 95
Marçal Berga Avatar answered Mar 18 '23 10:03

Marçal Berga