6

我按照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);
    }
}

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);
4

2 回答 2

6

例子 :-)

/**
 * @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);
}
于 2012-05-18T10:42:48.560 回答
1

@ZongshuLin 这里有类似的问题。可能的解决方案:

使用 DIRECTORY_SEPARATOR 常量,以便脚本可以在任何操作系统上运行——Windows 使用反斜杠,而 Linux 使用斜杠。

 /**
 * @return CsvFileIterator
 */
public function additionProvider()
{
    return new CsvFileIterator(__DIR__ . DIRECTORY_SEPARATOR . '..' . DIRECTORY_SEPARATOR . 'storage/data.csv');
}
于 2015-12-13T16:29:56.200 回答