【发布时间】:2018-06-16 13:32:04
【问题描述】:
我正在尝试创建一个单元测试来测试与数据库交互的 Symfony 4 代码。
需要测试的方法包含对自定义存储库类的调用,这会在运行 phpunit 时导致错误:错误:调用未定义的方法 Mock_ObjectRepository_583b1688::findLastRegisteredUsers()
我怀疑问题可能与我调用存储库的方式有关,但不确定如何解决。
测试/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 类的路径是在 User Entity 类中使用以下注释指定的
/**
* @ORM\Entity(repositoryClass="App\Repository\UserRepository")
*/
任何想法如何让测试使用自定义存储库类? 我想我可能需要更改 $userRepository = $this->createMock(ObjectRepository::class); 例如使用 $this->getMockBuilder() ?
【问题讨论】:
-
你期待注册方法('find'),而不是 findLastRegisteredUsers
-
哎呀,错过了 :) 但现在我收到一个错误:尝试配置无法配置的方法“findLastRegisteredUsers”,因为它不存在,尚未指定,是最终的,或者是静态的
-
您需要模拟 UserRepository 而不是基础 ObjectRepository。我一定在这里遗漏了一些东西。虽然有点跑题了,但您可能应该将 UserRepository 注入到您的 UserCalculator 中。
标签: unit-testing symfony doctrine phpunit