gpt4 book ai didi

php - 命名空间函数未在 PHPUnit 测试中运行

转载 作者:行者123 更新时间:2023-12-04 17:02:16 24 4
gpt4 key购买 nike

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

原类(class):

<?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.

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

最佳答案

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

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

function file_exists($path)
{
return true;
}

所以当然,您实际上从未覆盖函数 file_exists()在根命名空间中。

据我所知,你不能那样做。每当您尝试定义已存在的函数时,都会触发 fatal error ,请参阅 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 - 命名空间函数未在 PHPUnit 测试中运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44730429/

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