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

标签 php testing doctrine-orm doctrine phpunit

我正在尝试模拟 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/

相关文章:

在没有 webdriver 的浏览器中自动测试 JavaScript

php - Symfony Doctrine auto_mapping 无法识别

Symfony2 深度列表类别

php - UTF-8贯穿始终

php - 在 PHP 中,通过引用传递大量数据是否比通过值传递更节省资源(更智能)?

android - Android 应用的压力测试

c++ - 如何比较谷歌模拟中的特殊领域?

doctrine-orm - Silex和主义ORM

php - 使用自定义标签解析文本字段并转换为 HTML

php - 更新 chef php cookbook 的 php 版本