【问题标题】:PHP fopen() error in testing测试中的PHP fopen()错误
【发布时间】:2016-06-15 20:31:08
【问题描述】:

我有以下文件结构

src/functions.php

src/sample.csv

测试/函数Test.php

functions.php中,我有这个函数来读取一个csv文件

<?php
function readCSV($csvFile){
        $file_handle = fopen($csvFile, 'r');
        while (!feof($file_handle) ) {
            $line_of_text[] = fgetcsv($file_handle, 1024);
        }
        fclose($file_handle);
        return $line_of_text;
    }
?>

functionsTest.php文件中,我有

<?php

require_once('src/functions.php');
use phpunit\framework\TestCase;

class test extends TestCase {

    public function testReadDataFromFile() {
        $filename = "./sample.csv";
        $data = readCSV($filename);
        $this->assertEquals("test data", $data);
    }
}
?>

当我使用 >phpunit tests/functionsTest.php 运行测试代码时,我收到错误提示

fopen(./sample.csv): failed to open stream: No such file or directory

但是如果我从同一个 src/functions.php 调用函数,我会得到数据

 print_r(readCSV("sample.csv"));

所以我尝试将 sample.csv 文件移动到测试文件夹 -

测试/sample.csv

但我仍然遇到同样的错误

我想我错过了一些简单的东西。 谁能帮我解决这个问题?

【问题讨论】:

    标签: php csv phpunit fopen


    【解决方案1】:

    这是因为单点. 代表当前目录。从tests/ 调用脚本并指定. 将在tests 目录中查找sample.csv,而实际上它位于src/ 中。

    你想使用$filename = "../src/sample.csv";指定目录

    另请注意,您可能希望使用 magic constants 代替,或指定文件的绝对路径(例如 /YourName/YourProject/src/sample.csv),而不是相对路径。

    附:在运行脚本以解决此类问题时,您可以打印出 __FILE____DIR__ 等神奇常量。

    【讨论】:

      猜你喜欢
      • 2012-09-07
      • 1970-01-01
      • 2021-04-28
      • 1970-01-01
      • 1970-01-01
      • 2023-04-02
      • 2012-01-17
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多