PHPUnit测试错误:类(..)的对象无法转换为字符串


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

首先,我是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);
    }
}
?>

我的考试所在的班级:

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