gpt4 book ai didi

php - 单元测试 Doctrine : can't mock repository method

转载 作者:行者123 更新时间:2023-11-28 20:04:32 24 4
gpt4 key购买 nike

我正在尝试模拟 Doctrine 存储库和 entityManager,但 PHPUnit 一直告诉我:

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

这是片段:

<?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));
}
}

有什么帮助吗?我尝试了此代码的一些变体,但无法通过此特定错误。

谢谢。

最佳答案

您使用的是哪个版本的 PHPUnit?

无论如何,检查这个可能的解决方案:

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

应该可以。

关于php - 单元测试 Doctrine : can't mock repository method,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48277568/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com