douyan8961 2017-06-23 21:53
浏览 31
已采纳

Namespaced函数未在PHPUnit测试上运行

I'm trying to override a built in php function using a namespaced test like this:

Original Class:

<?php
namespace My\Namespace;

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

Unit Test

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

In this case the file_exists function in my test should always return true, however when I run PHPUnit I get:

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.

It's as if the namespaced function is being ignored and it's just calling the built in function instead, am I missing something?

  • 写回答

1条回答 默认 最新

  • dongtan8979 2017-06-24 07:31
    关注

    According to your code sample, you define the function file_exists() in the namespace My\Namespace\Test\Unit\Console\Command:

    namespace My\Namespace\Test\Unit\Console\Command;
    
    function file_exists($path)
    {
        return true;
    }
    

    so of course, you actually never override the function file_exists() in the root namespace.

    As far as I know, you can't do that. Whenever you would try to define a function that already exists, a fatal error will be triggered, see https://3v4l.org/JZHcp.

    However, if what you want to achieve is asserting that OverrideCommand::myFileExists() returns true if a file exists, and false if it doesn't, you can do one of the following

    Refer to files which do and do not exist in your test

    public function testMyFileExistsReturnsFalseIfFileDoesNotExist()
    {
         $command = new OverrideCommand();
    
         $this->assertTrue($command->myFileExists(__DIR__ . '/NonExistentFile.php');
    }
    
    public function testMyFileExistsReturnsTrueIfFileExists()
    {
         $command = new OverrideCommand();
    
         $this->assertTrue($command->myFileExists(__FILE__);
    }
    

    Mock the file system

    Use https://github.com/mikey179/vfsStream to mock the file system.

    Note: For your example, I would recommend the former.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器