首页 > 解决方案 > PHPunit 将读取文件重构为 EOF 测试功能

问题描述

我是 TDD 和 PHPUnit 的新手,所以如果我的测试函数逻辑没有意义,请原谅我。

我有一个名为 test_read_to_end_of_file_is_reached 的测试函数,它在我的 inputTest 类中写入时通过绿色,批准它读取到文件末尾。

我正在尝试将读取/打开部分重构为我的供应商模型中名为 readFile 的函数

原来,InputTest

<?php

class InputTest extends \PHPUnit\Framework\TestCase{

    protected $vendors;

    public function setUp(){
        $this->vendors = new \App\Models\Vendors;
    }

    /** @test */
    public function test_that_input_file_exists(){
        $this->assertFileExists($this->vendors->getFileName());
    }

    /** @test */
    public function test_read_to_end_of_file_is_reached(){
        $fileName = $this->vendors->getFileName();
        $file = fopen($fileName, "r");
        // loop until end of file
        while(!feof($file)){
            // read one character at a time
            $temp = fread($file, 1);
        }

        $this->assertTrue(feof($file));
        //close file
        fclose($file);
    }

我尝试将它分成一个函数

供应商类:

<?php

namespace App\Models;
class Vendors
{
    protected $fileName = "app/DataStructures/input.txt";

    public function setFileName($fileName){
        $this->fileName = trim($fileName);
    }

    public function getFileName(){
        return trim($this->fileName);
    }

    public function readFile(){
        $fileName = $this->getFileName();
        $file = fopen($fileName, "r");

        // loop until end of file
        while(!feof($file)){
            // read one character at a time
            $temp = fread($file, filesize($fileName));
            var_dump($temp);
        }
        return $file;
        fclose($file);
    }
}

我重构的测试:

    /** @test */
    public function test_read_to_end_of_file_is_reached(){
        $fileName = $this->vendors->getFileName();
        $file = fopen($fileName, "r");
        $this->assertTrue(feof($this->vendors->readFile()));
        //close file
        fclose($file);
    }

这一切都有效,我只是不确定我是否可以进一步简化测试。这最终将允许我在读取文本文件的基础上进行构建,并根据读取的内容逐行解析以重现控制台上的内容。

标签: phpunit-testingphpunitrefactoringeof

解决方案


推荐阅读