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

开发技术 作者: 2024-07-04 11:15:01
我按照 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
我按照 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);
}
原创声明
本站部分文章基于互联网的整理,我们会把真正“有用/优质”的文章整理提供给各位开发者。本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
本文链接:http://www.jiecseo.com/news/show_38410.html