I am trying to create a Unit Test to test Symfony 4 code that interacts with the Database.
The method that needs testing contains a call to a custom repository Class and this is causing an error when running phpunit: Error: Call to undefined method Mock_ObjectRepository_583b1688::findLastRegisteredUsers()
I suspect the problem might be with how I'm calling the repository, but not sure how to fix it.
tests/UserTest.php
class UserTest extends TestCase
{
public function testCalculateTotalUsersReturnsInteger()
{
$user = new User();
$user->setFullname('Test');
// ! This might be what is causing the problem !
$userRepository = $this->createMock(ObjectRepository::class);
$userRepository->expects($this->any())
->method('find')
->willReturn($user);
$objectManager = $this->createMock(ObjectManager::class);
$objectManager->expects($this->any())
->method('getRepository')
->willReturn($userRepository);
$userCalculator = new RegistrationHandler($objectManager);
$result = $registrationHandler->getAccountManager();
$this->assertInternalType('int', $result);
}
}
Repository/UserRepository.php
class UserRepository extends EntityRepository
{
public function findLastRegisteredUsers($maxResults)
{
return $this->createQueryBuilder('user')
->andWhere('user.customField IS NOT NULL')
->addOrderBy('user.id', 'DESC')
->setFirstResult(0)
->setMaxResults($maxResults)
->getQuery()
->execute();
}
}
src/User/UserCalculator.php
// src/User/UserCalculator.php
namespace App\User;
use Doctrine\Common\Persistence\ObjectManager;
class UserCalculator
{
private $objectManager;
public function __construct(ObjectManager $objectManager)
{
$this->objectManager = $objectManager;
}
public function calculateTotalUsers()
{
$userRepository = $this->objectManager
->getRepository(User::class);
$users = $userRepository->findLastRegisteredUsers(100);
// custom code
}
}
Just to be clear, the path to the custom EntityRepository class is specified in the User Entity class using the following annotation
/**
* @ORM\Entity(repositoryClass="App\Repository\UserRepository")
*/
Any ideas how to get the Test to use the custom repository class? I think I might need to change something in $userRepository = $this->createMock(ObjectRepository::class); e.g. using $this->getMockBuilder() ?