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 Python turtle 画图
  • ¥15 关于大棚监测的pcb板设计
  • ¥15 stm32开发clion时遇到的编译问题
  • ¥15 lna设计 源简并电感型共源放大器
  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)
  • ¥15 Vue3地图和异步函数使用
  • ¥15 C++ yoloV5改写遇到的问题
  • ¥20 win11修改中文用户名路径
  • ¥15 win2012磁盘空间不足,c盘正常,d盘无法写入
  • ¥15 用土力学知识进行土坡稳定性分析与挡土墙设计