您当前的位置: 首页 > 慢生活 > 程序人生 网站首页程序人生
phpunit使用Iterator迭代器接口作为数据供给器与csv文件的读取
发布时间:2021-09-13 17:00:28编辑:雪饮阅读()
那么假如我有这样的数据
这是一个csv文件,所谓csv文件一般的都是逗号分隔的数据,怎么看都和纯文本差不多的。
Notepad++打开后像是这样
那么向是前面我们将数据供给器都是用数组形式提供,这次我们将用iterator形式提供,就以iterator读取csv实现iterator数据供给器。
DataTest.php:
<?php declare(strict_types=1);
use PHPUnit\Framework\TestCase;
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() {
foreach ($this->current as $key=>$val){
$this->current[$key]=intval($val);
}
return $this->current;
}
public function next() {
$this->current = fgetcsv($this->file);
$this->key++;
}
}
final class DataTest extends TestCase
{
/**
* @dataProvider additionProvider
*/
public function testAdd(int $a, int $b, int $expected): void
{
$this->assertSame($expected, $a + $b);
}
public function additionProvider(): CsvFileIterator
{
return new CsvFileIterator('data.csv');
}
}
use PHPUnit\Framework\TestCase;
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() {
foreach ($this->current as $key=>$val){
$this->current[$key]=intval($val);
}
return $this->current;
}
public function next() {
$this->current = fgetcsv($this->file);
$this->key++;
}
}
final class DataTest extends TestCase
{
/**
* @dataProvider additionProvider
*/
public function testAdd(int $a, int $b, int $expected): void
{
$this->assertSame($expected, $a + $b);
}
public function additionProvider(): CsvFileIterator
{
return new CsvFileIterator('data.csv');
}
}
然后运行如:
C:\Users\Administrator>D:\phpstudy_pro\Extensions\php\php7.3.4nts\php.exe D:\phpstudy_pro\Extensions\php\php7.3.4nts\phpunit-9.5.8.phar C:\Users\Administrator\PhpstormProjects\untitled\DataTest.php
PHPUnit 9.5.8 by Sebastian Bergmann and contributors.
...F 4 / 4 (100%)
Time: 00:00.004, Memory: 20.00 MB
There was 1 failure:
1) DataTest::testAdd with data set #3 (1, 1, 3)
Failed asserting that 2 is identical to 3.
C:\Users\Administrator\PhpstormProjects\untitled\DataTest.php:42
FAILURES!
Tests: 4, Assertions: 4, Failures: 1.
和前面用数组做为数据共给器是无差别的。
不过需要注意的就是这里data.csv要放在当前执行命令所在目录,像是这里的:C:\Users\Administrator目录
关键字词:phpunit,Iterator,csv,数据供给器