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

php-如何在单元测试中断言生成文件的内容

(php - How to assert content of generated file in unit test)

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

我有一个生成 csv 文件并返回 URL 以下载文件的函数。问题是我正在使用Uuid::uuid4()->toString()大量文件。如何使用 Codeception 编写单元测试来验证给定函数是否有效?

测试精髓:我必须将数组传递给函数来创建一个csv,函数返回带有数据的文件的路径,有必要检查函数返回的文件路径是否正确。

是否可以检查文件是否包含某些信息,即数据导出的正确性,如果是,如何进行?

要测试的类:

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';
    }
}

我尝试编写测试失败:

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

}

提前致谢!

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

由于你使用的是 Codeception,你可以使用Filesystem 模块的seeFileFoundseeFileContentsEqual方法。

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

文件系统模块必须使用composer require --dev codeception/module-filesystem 套件配置安装并启用。