我正在尝试创建一个单元测试来测试与数据库交互的Symfony 4代码。
需要测试的方法包含对自定义存储库类的调用,这会在运行phpunit时导致错误:错误:调用未定义的方法Mock_ObjectRepository_583b1688 ::findLastRegisteredUsers()
我怀疑问题可能出在我调用存储库的方式上,但不确定如何解决它。
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
}
}
明确一点,自定义EntityRepository类的路径在用户实体类中使用以下注释指定:
/**
* @ORM\Entity(repositoryClass="App\Repository\UserRepository")
*/
有什么办法可以让测试使用自定义的存储库类?我认为我可能需要在 $userRepository = $this->createMock(ObjectRepository::class); 中做出一些改变,例如使用 $this->getMockBuilder() ?