How to use csv file in PHPUnit test

I wrote a DataTest case following example 4.5 of the PHPUnit manual, url:
http://www.phpunit.de/manual/3.6/en/writing-tests-for-phpunit.html#writing-tests-for-phpunit.data-providers .
But I ran into an error:

The data provider specified for DataTest :: testAdd is not valid.
Invalid dataset # 0.

I thought that maybe I did not edit the data.csv file correctly, then I used the php fputcsv () function to create the data.csv file, but it also did not work, I want to know why and how to solve this problem. Thanks!

R. S .: data in data.csv:

0,0,0
0,1,1

<h / "> Codes are displayed as follows:
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++; } } 

The data.csv file is created by the fputcsv () function:

 $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
source share
2 answers

Example :-)

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

@ZongshuLin A similar question here. Possible solutions:

  • Check data.csv . Basically I had to add a line after the last line.
  • You can also check my approach on GitHub when specifying the location of data.csv

Use the DIRECTORY_SEPARATOR constant so that the script can run on any OS. Windows uses a backslash, while Linux uses a slash.

  /** * @return CsvFileIterator */ public function additionProvider() { return new CsvFileIterator(__DIR__ . DIRECTORY_SEPARATOR . '..' . DIRECTORY_SEPARATOR . 'storage/data.csv'); } 
0
source

Source: https://habr.com/ru/post/1413094/


All Articles