为什么 file_get_contents 函数在 PHPUnit 测试中使用时给我一个语法错误,但在其他情况下工作正常?

Why does file_get_contents function give me a syntax error when used in PHPUnit test, but works fine otherwise?

我有一个 class 正在尝试 运行 测试。其中一个函数应该接受一个相当长的字符串作为其参数之一。在生产中,这个字符串将来自数据库,但现在,我只是从 .txt 文件中读取。

在早期阶段,我只是通过将此添加到 class 所在的同一文件的底部来进行测试:

$testFile = file_get_contents('./test.txt');

然后将 $testFile 传递给函数,效果很好。但是现在我正在尝试进行一些实际的单元测试,这是我必须测试的内容,请记住,我对 PHPUnit 的经验非常有限:

class StackTest extends PHPUnit_Framework_TestCase {

    public $file = file_get_contents('/path/to/test.txt');

    public function setUp() {
        //instantiate object using $file
    }

    public function testFileParser() {
        //test the function
    }
}

但是当我 运行 PHPUnit 测试时,它给我这个错误:

PHP Parse error:  syntax error, unexpected '(', expecting ',' or ';' in /path/to/tests/tests.php on line 9

第 9 行是 file_get_contents 所在的行。有人知道为什么要这样做吗?

您不能使用函数来初始化 属性。

您可以按照您的情况进行操作:

class StackTest extends PHPUnit_Framework_TestCase {

public $file;

public function setUp() {
     $this->file = file_get_contents('/path/to/test.txt');
}

public function testFileParser() {
    //test the function
}

}