Symfony - mock repository method return value

Viewed 52

In my Symfony project I am using "phpunit/phpunit": "^9.5" to write test.

I am trying to mock return value of the method in the repository class:

class WorkspaceMemberRepository extends ServiceEntityRepository
{
public function __construct(ManagerRegistry $registry)
{
    parent::__construct($registry, WorkspaceMember::class);
}

public function hasRole(
    int $memberId,
    string $action,
    string $subject
): bool
{
    return 0 !== (int)$this
            ->createQueryBuilder('wm')
            ->select('count(1)')
            ->join('App\Shared\Entity\Role', 'r', Join::WITH, 'wm.workspace = r.workspace')
            ->join('App\Shared\Entity\RoleAbility', 'ra', Join::WITH, 'r.id = ra.role')
            ->where('wm.member = :memberId')
            ->andWhere('ra.action = :action')
            ->andWhere('ra.subject = :subject')
            ->setParameters([
                'memberId' => $memberId,
                'action'   => $action,
                'subject'  => $subject
            ])
            ->getQuery()
            ->getSingleScalarResult();
 }
} 

I am calling it in the other method I want to test so I would like to mock it's return value so I can re-use it in other test cases:

$workspaceMemberRepository = $this->createMock(WorkspaceMemberRepository::class);
    $workspaceMemberRepository->expects($this->any())
        ->method('hasRole')
        ->willReturn(true);

 $this->assertTrue($workspaceMemberRepository->hasRole(1, 'edit', 'customers'));

Return value must be of type bool, none returned

Is there another way to properly mock this function?

0 Answers
Related