使用CSV文件,我下面的例子PHPUnit的4.5手動的,網址是寫了一個數據測試的情況。
但我有一個錯誤遇到:如何在PHPUnit的測試
The data provider specified for DataTest::testAdd is invalid.
Data set #0 is invalid.
我想這也許是我在一個錯誤的方式編輯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);
}
}
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, 0),
array(0, 1, 1)
);
$fp = fopen('data.csv', 'w');
foreach($data as $v)
{
fputcsv($fp, $v);
}
fclose($fp);
請出示您的數據提供程序函數的代碼。解釋你犯錯的地方很重要。通過編輯將其添加到您的問題中(您可以縮短文件名和其他不重要的文件名和其他特定數據以便了解您的問題)。 – hakre
@hakre,我已經在我的問題中添加了代碼,請幫我分析並告訴我爲什麼會出現錯誤,謝謝! –
檢入你的迭代器可以訪問文件的構造函數。例如,您可能需要將其傳遞到完整路徑(例如'__DIR__。'/ data.csv')。或者,使用'true'作爲[fopen的第三個參數](http://uk3.php.net/manual/en/function.fopen.php)來使用包含路徑。 – cmbuckley