每次phpunit测试后类变量都会重置

时间:2015-11-08 21:38:46

标签: php phpunit

在我的PHPUnit测试中,我有一个测试和一个数据提供程序,它提供一些整数值来测试。我正在和他们做一些逻辑测试。之后,我想将所有这些整数值存储在类范围变量中。

private $numbers = [];

/**
 * @dataProvider dp
 */
public function testOne($data)
{
    foreach($data as $n)
        array_push($this->numbers, $n);

    var_dump($this->numbers);
}
public function dp()
{
    return [
        "first" => [[1,2]],
        "second" => [[3,4]],
    ];
}

输出:

.array(2) {
  [0] =>
  int(1)
  [1] =>
  int(2)
}
.                                                                  2 / 2 (100%)array(2) {
  [0] =>
  int(3)
  [1] =>
  int(4)
}


Time: 9.71 seconds, Memory: 34.00Mb

如您所见,它将第一个数据集的值(1,2)附加到$numbers,当第二个数据集开始测试时,重置数组并$number成为(3,4)。但是我期待它会是(1,2,3,4)。

你能告诉我为什么$numbers数组在second数据集之前为空?

我没有tearDown()方法。

php -v
PHP 5.6.14-1+deb.sury.org~precise+1 (cli) 
Copyright (c) 1997-2015 The PHP Group
Zend Engine v2.6.0, Copyright (c) 1998-2015 Zend Technologies
    with Zend OPcache v7.0.6-dev, Copyright (c) 1999-2015, by Zend Technologies
    with Xdebug v2.3.2, Copyright (c) 2002-2015, by Derick Rethans

phpunit --version
PHPUnit 5.0.4 by Sebastian Bergmann and contributors.

1 个答案:

答案 0 :(得分:2)

您需要将您的财产声明为静态:

private static $numbers = [];

/**
 * @dataProvider dp
 */
public function testOne($data)
{
    foreach($data as $n)
        array_push(self::$numbers, $n);

    var_dump(self::$numbers);
}

public function dp()
{
    return [
        "first" => [[1,2]],
        "second" => [[3,4]],
    ];
}