我按照
PHPUnit手册的示例4.5编写了一个DataTest案例,网址是:
http://www.phpunit.de/manual/3.6/en/writing-tests-for-phpunit.html#writing-tests-for-phpunit.data-providers.但是我遇到了一个错误:
The data provider specified for DataTest::testAdd is invalid.
Data set #0 is invalid.
我以为可能是我以错误的方式编辑data.csv文件,然后我使用PHP函数fputcsv()来创建data.csv文件,但它也没有用,我想知道为什么,以及如何解决这个问题.谢谢!
P. S.:data.csv中的数据是:
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);
}
}
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++;
}
}
data.csv文件由函数fputcsv()创建:
$data = array(
array(0,0),array(0,1)
);
$fp = fopen('data.csv','w');
foreach($data as $v)
{
fputcsv($fp,$v);
}
fclose($fp);
示例:-)
/**
* @dataProvider provider
* @group csv
*/
public function testAdd($a,$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,1)
);
$file = fopen("/Volumes/htdocs/contacts.csv","w");
foreach ($list as $line)
{
fputcsv($file,$line);
}
fclose($file);
}