Warm tip: This article is reproduced from serverfault.com, please click

How to assert content of generated file in unit test

发布于 2021-02-04 18:27:01

I have a function that generates a csv file and returns the URL to download the file. Problem is i'm using Uuid::uuid4()->toString() due to a lot of files. How can I write a unit test using Codeception to verify that a given function works?

Essence of the test: I must pass an array to the function to create a csv, the function returns the path to the file with data, it is necessary to check that the function returns the correct path to the file.

Can I check that the file contains certain information, that is, the correctness of data export, if so, how can this be done?

Class to test:

class CsvExport
{
    const UPLOAD_DIRECTORY = "uploads/csv/";

    public function create(array $data): string
    {
        $id = Uuid::uuid4()->toString();

        if (empty($data)) {
            throw new \DomainException('Array is empty');
        }

        $file = $this->buildFileByPath($id);
        $write = fopen($file, 'w+');

        foreach ($data as $items) {
            fputcsv($write, $items);
        }
        fclose($write);

        return $file;
    }

    private function buildFileByPath(string $id): string
    {
        return self::UPLOAD_DIRECTORY . $id . '.csv';
    }
}

And my unsuccessful attempt to write a test:

class CsvExportTest extends Unit
{
    /**
     * @var UnitTester
     */
    protected UnitTester $tester;

    
    public function testCsvExport():void
    {
        $data = $data = [['Name', 'age', 'Gender']];
        $service = new CsvExport();
        $path = $service->create($data);
        Assert::assertEquals($path, $service->create($data));
    }

}

Thanks in advance!

Questioner
user8239381
Viewed
0
Naktibalda 2021-02-06 21:33:39

Since you are using Codeception, you can use seeFileFound and seeFileContentsEqual methods of Filesystem module.

<?php
    class CsvExportTest extends Unit
    {
        /**
         * @var UnitTester
         */
        protected UnitTester $tester;
    
        
        public function testCsvExport():void
        {
            $data = [['Name', 'age', 'Gender']];
            $service = new CsvExport();
            $path = $service->create($data);
            $this->tester->seeFileFound($path);
            $this->tester->seeFileContentEquals("Name,age,Gender\n");
        }
    }

Filesystem module must be installed using composer require --dev codeception/module-filesystem and enabled in suite configuration.