我按照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文件,但它也没有用,我想知道为什么,以及如何解决这个问题。谢谢!
P上。 S:data.csv中的数据是:
0,0,0
0,1,1
<小时/> 代码如下:
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);
答案 0 :(得分: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);
}
答案 1 :(得分:0)
@ZongshuLin这里有类似的问题。可能的解决方案:
使用DIRECTORY_SEPARATOR常量,以便脚本可以在任何操作系统上运行 - Windows在Linux斜杠时使用反斜杠。
/**
* @return CsvFileIterator
*/
public function additionProvider()
{
return new CsvFileIterator(__DIR__ . DIRECTORY_SEPARATOR . '..' . DIRECTORY_SEPARATOR . 'storage/data.csv');
}