【问题标题】:PHPUnit Test error: Object of class (...) could not be converted to stringPHPUnit 测试错误:类 (...) 的对象无法转换为字符串
【发布时间】:2016-03-31 19:34:26
【问题描述】:

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

}

?>

有人可以帮我解决吗?

【问题讨论】:

  • 我不确定是否要执行 assertFalse(var_dump(...)) - var_dump 不返回布尔值。
  • 我删除了var_dump,但错误仍然存​​在。

标签: php phpunit vfs


【解决方案1】:

你得到的错误是因为你最初创建了这个局部变量:

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

【讨论】:

  • 我知道这是一个简单的错误!哈哈谢谢你,@duncan。现在我需要解决 vfsStream 的其他问题 lol
  • @B.Pereira 如果此答案解决了您的问题,请接受。如果您不熟悉 stackoverflow,请在此处浏览:stackoverflow.com/tour
猜你喜欢
  • 2013-07-03
  • 2014-11-21
  • 2015-02-05
  • 2012-07-12
  • 1970-01-01
  • 1970-01-01
  • 2017-09-21
  • 1970-01-01
相关资源
最近更新 更多