gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 17:12:46 24 4
gpt4 key购买 nike

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

最佳答案

示例:-)

/**
* @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);
}

关于phpunit - 如何在 PHPUnit 测试中使用 csv 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10646105/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com