如何在PHPUnit测试中使用csv文件

Zon*_*Lin 5 phpunit

我按照PHPUnit手册的例子4.5编写了一个DataTest案例,网址是:
http://www.phpunit.de/manual/3.6/en/writing-tests-for-phpunit.html#writing-tests-for-phpunit .data-providers.
但我遇到了一个错误:

为DataTest :: testAdd指定的数据提供程序无效.
数据集#0无效.

我以为可能是我以错误的方式编辑data.csv文件,然后我使用php函数fputcsv()来创建data.csv文件,但它也没有用,我想知道为什么,以及如何解决这个问题.谢谢!

PS:data.csv中的数据是:

0,0,0
0,1,1


代码如下所示:
DataTest.php

require 'CsvFileIterator.php';
class DataTest extends PHPUnit_Framework_TestCase
{
public function provider()
    {
        return new CsvFileIterator('data.csv');
    }

    /**
    * @dataProvider provider
    */
    public function testAdd($a, $b, $c)
    {
         $this->assertEquals($c, $a + $b);
    }
}
Run Code Online (Sandbox Code Playgroud)

CsvFileIterator.php

class CsvFileIterator implements Iterator
{
    protected $file;
    protected $key = 0;
protected $current;

public function __construct($file)
{
    $this->file = fopen($file, 'r');
}

public function __destruct()
{
    fclose($this->file);
}

public function rewind()
{
    rewind($this->file);
    $this->current = fgetcsv($this->file);
    $this->key = 0;
}

public function valid()
{
    return !feof($this->file);
}

public function key()
{
    return $this->key;
}

public function current()
{
    return $this->current;
}

public function next()
{
    $this->current = fgetcsv($this->file);
    $this->key++;
}
}
Run Code Online (Sandbox Code Playgroud)

data.csv文件由函数fputcsv()创建:

$data = array(
array(0, 0, 0),
array(0, 1, 1)
);

$fp = fopen('data.csv', 'w');

foreach($data as $v)
{
fputcsv($fp, $v);
}
fclose($fp);
Run Code Online (Sandbox Code Playgroud)

小智 5

示例:-)

/**
 * @dataProvider provider
 * @group csv
 */
public function testAdd($a, $b, $c)
{
    $this->assertEquals($c, $a + $b);
}

/**
 * @return array
 */
public function provider()
{
    $file = file_get_contents("/Volumes/htdocs/contacts.csv","r");
    foreach ( explode("\n", $file, -1) as $line )
    {
        $data[] = explode(',', $line);
    }
    return $data;
}

/*
 * CREATE TO CSV FILE DATAPROVIDER
 * don't create this file in your test case
 */
public function saveToCsv()
{
    $list = array(
        array(0,0,0),
        array(0,1,1)
    );

    $file = fopen("/Volumes/htdocs/contacts.csv","w");

    foreach ($list as $line)
    {
        fputcsv($file,$line);
    }

    fclose($file);
}
Run Code Online (Sandbox Code Playgroud)