Home » Php » PHPunit refactoring read file to EOF test to function

PHPunit refactoring read file to EOF test to function

Posted by: admin May 27, 2018 Leave a comment

Questions:

I am new to TDD and PHPUnit so please forgive me if my test function logic makes no sense.

I have a test function called test_read_to_end_of_file_is_reached which passes green as it’s written in my inputTest class, approving that it reads to end of file.

I am trying to refactor the read/open part into a function in my Vendors model called readFile

Originally, InputTest class

<?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);
    }

My attempt to separate it into a function

Vendors class:

<?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);
    }
}

my refactored test:

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

This all works, I’m just not sure whether I can simplify the test more.
which will eventually allow me to build upon reading the text file and parsing line by line based on what is read to reproduce the contents on the console.

Answers: