PHPUnit 测试错误 : Object of class (. ..) 无法转换为字符串

标签 php phpunit vfs

首先,我是 PHPUnit 测试和 PHP 的新手,如果我遗漏了一些太明显的东西,抱歉。

好的,现在回答我的问题:我正在使用名为 VfsStream 的虚拟文件系统测试功能 unlink( ) 。由于某种原因,在我的测试中发生了此错误:

[bianca@cr-22ncg22 tests-phpunit]$ phpunit
PHPUnit 4.6.10 by Sebastian Bergmann and contributors.

Configuration read from /var/www/html/tests-phpunit/phpunit.xml

E

Time: 27 ms, Memory: 4.50Mb

There was 1 error:

1) test\UnlinkTest\UnlinkTest::testUnlink
Object of class App\Libraries\Unlink could not be converted to string

/var/www/html/tests-phpunit/test/UnlinkTest.php:21
/home/bianca/.composer/vendor/phpunit/phpunit/src/TextUI/Command.php:153
/home/bianca/.composer/vendor/phpunit/phpunit/src/TextUI/Command.php:105

FAILURES!
Tests: 1, Assertions: 0, Errors: 1.

我知道我的 Unlink 类及其返回的内容,但我不知道是什么。

我正在测试的类:

class Unlink {

    public function unlinkFile($file) {

        if (!unlink($file)) {
            echo ("Error deleting $file");
        }
        else {
            echo ("Deleted $file");
        }

        return unlink($file);
    }

}

?>

我的测试所在的类(class):

use org\bovigo\vfs\vfsStream;
use App\Libraries\Unlink;

class UnlinkTest extends \PHPUnit_Framework_TestCase {

    public function setUp() {
        $root = vfsStream::setup('home');
        $removeFile = new Unlink();
    }

    public function tearDown() {
        $root = null;
    }

    public function testUnlink() {
        $root = vfsStream::setup('home');
        $removeFile = new Unlink();
        vfsStream::newFile('test.txt', 0744)->at($root)->setContent("The new contents of the file");
        $this->$removeFile->unlinkFile(vfsStream::url('home/test.txt'));
        $this->assertFalse(var_dump(file_exists(vfsStream::url('home/test.txt'))));
    }

}

?>

有人可以帮我解决这个问题吗?

最佳答案

您收到的错误是因为最初您创建了此局部变量:

$removeFile = new Unlink();

但是当您这样做时,您将其称为 $this->$removeFile:

$this->$removeFile->unlinkFile(vfsStream::url('home/test.txt'));

这是不正确的;您可以在有类变量并且想要动态引用它的地方使用它。例如

class YourClass {
    public $foo;
    public $bar;

    public function __construct() {
        $this->foo = 'hello';
        $this->bar = 'world';
    }

    public function doStuff() {
        $someVariable = 'foo';

        echo $this->$someVariable;  // outputs 'hello'
    }
}

您需要做的就是删除 $this,并将其更改为:

$removeFile->unlinkFile(vfsStream::url('home/test.txt'));

关于PHPUnit 测试错误 : Object of class (. ..) 无法转换为字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36342169/

相关文章:

php -> fwrite 处理管道挂起 -> 为什么?

php - 这个sql查询可以接受吗?

php - phpunit 中的 dbunit 没有截断表

gradle - 为gradle-vfs插件配置代理

php - 官方镜像中禁止 Docker PHP

php - Facebook,我应该在 SQL 中使用 Array 还是不同的行来表示喜欢的帖子

php - 为 mysql 和 sqlite 添加日期

php - 如何阻止 PHPUnit 发出捕获异常的堆栈跟踪?

c++ - 虚拟文件系统是该应用程序的正确概念吗

java - Windows机器上无法通过VFS下载文件?