2

In my PHPUnit tests, I have a test and a data provider which provide some integer values to test. And I'm doing some logical tests with them. After that I want to store all these integer values in a class-scope variable.

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]],
    ];
}

Output:

.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

As you see, it's appending first data set's values (1,2) to $numbers and when 2nd data set started to test, something resetting the array and $number becoming (3,4) . However I was expecting it will be (1,2,3,4).

Can you tell me why $numbers array is empty before second data set?

I don't have a tearDown() method.

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.
4
  • @Spudley :)) He / She removed down vote a few minutes later my comment, and then I removed my comment . Thank you. Commented Nov 8, 2015 at 21:53
  • Dunno if it's relevant but 'firsrt' and 'second' are keys pointing at an array within an array (trying ro say there's 2 sets of brackets) are you just passing dp()['first'] to testOne? Commented Nov 8, 2015 at 22:25
  • @Terminus I have to set array of array to get $data as an array. This is how data providers works. If i use one dimensional array, it will send 1 as first argument and 2 as second argument to testOne(). Commented Nov 8, 2015 at 22:30
  • Gotcha. So when you var_dump($data) in testOne you would only see 1 and than 2 and than 3 and than 4. Commented Nov 8, 2015 at 22:54

1 Answer 1

4

You need to declare your property as static:

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]],
    ];
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.