【问题标题】:Namespaced function not running on PHPUnit test命名空间函数未在 PHPUnit 测试上运行
【发布时间】:2017-11-27 13:33:16
【问题描述】:

我正在尝试使用这样的命名空间测试覆盖内置的 php 函数:

原始类:

<?php
namespace My\Namespace;

class OverrideCommand
{
    public function myFileExists($path)
    {
        return file_exists($path);
    }
}

单元测试

<?php
namespace My\Namespace\Test\Unit\Console\Command;

function file_exists($path)
{
    return true;
}

class OverrideCommandTest extends \PHPUnit_Framework_TestCase
{
    /**
     * @var OverrideCommand
     */
    protected $command;

    protected function setUp()
    {
        $this->command = new \My\Namespace\OverrideCommand();
    }

    public function testMyFileExists()
    {
        $result = $this->command->myFileExists('some/path/file.txt');

        $this->assertTrue($result);
    }
}

在这种情况下,我的测试中的 file_exists 函数应该总是返回 true,但是当我运行 PHPUnit 时,我得到:

PHPUnit 5.7.21 by Sebastian Bergmann and contributors.

There was 1 failure:

1) My\Namespace\Test\Unit\Console\Command\OverrideCommandTest::testMyFileExists
Failed asserting that false is true.

就好像命名空间函数被忽略了,它只是调用内置函数,我错过了什么吗?

【问题讨论】:

标签: php unit-testing namespaces mocking phpunit


【解决方案1】:

根据您的代码示例,您在命名空间My\Namespace\Test\Unit\Console\Command 中定义函数file_exists()

namespace My\Namespace\Test\Unit\Console\Command;

function file_exists($path)
{
    return true;
}

当然,您实际上永远不会覆盖根命名空间中的函数 file_exists()

据我所知,你不能这样做。每当您尝试定义一个已经存在的函数时,都会触发一个致命错误,请参阅https://3v4l.org/JZHcp

但是,如果您想要实现的是断言 OverrideCommand::myFileExists() 如果文件存在则返回 true,如果文件不存在则返回 false,您可以执行以下操作之一

参考测试中存在和不存在的文件

public function testMyFileExistsReturnsFalseIfFileDoesNotExist()
{
     $command = new OverrideCommand();

     $this->assertTrue($command->myFileExists(__DIR__ . '/NonExistentFile.php');
}

public function testMyFileExistsReturnsTrueIfFileExists()
{
     $command = new OverrideCommand();

     $this->assertTrue($command->myFileExists(__FILE__);
}

模拟文件系统

使用https://github.com/mikey179/vfsStream 模拟文件系统。

注意:对于你的例子,我推荐前者。

【讨论】:

  • 感谢我监督了这个细节,我最终使用php-mock-phpunit 能够轻松更改测试中内置函数的命名空间。这只是一个使用 file_exists 的孤立示例,但我还在整个代码中使用了其他函数,因此 vfsStream 对我的情况来说可能有点过头了。
猜你喜欢
  • 2018-07-29
  • 1970-01-01
  • 2012-08-20
  • 2014-08-23
  • 2018-09-17
  • 1970-01-01
  • 2018-09-14
  • 2015-11-13
  • 2013-10-26
相关资源
最近更新 更多