PHPUnit Test error: Object of class (...) could not be converted to string

PHPUnit Test error: Object of class (...) could not be converted to string

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

好的,现在回答我的问题:我正在使用一个名为 VfsStream to test the function 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 有问题以及它返回了什么,但我不知道是什么。

我正在测试的class:

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 变量并且你想动态引用它的地方使用它。例如

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'));