为什么file_get_contents函数在PHPUnit测试中使用时会给我一个语法错误,但是否则可以正常工作?

时间:2016-01-27 16:32:38

标签: php phpunit

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

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

$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所在的行。任何人都知道为什么要这样做?

1 个答案:

答案 0 :(得分:1)

您无法使用函数初始化属性。

您可以使用类似于您的方法来执行此操作:

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
}

}