PHPUnit 测试写入文件的函数并将内容检查到创建的文件中

PHPUnit test a function that write in file and check the content into created file

我正在为 sonata/exporter 做贡献,这是一个用于以多种格式(CSV、JSON、XML、XLS 等)导出数据的库。

我致力于通过封装另一个 Writer(如 CsvWriter 或 XlsWriter)将布尔值转换为字符串(例如 yes/no)的 Writer。

这是我第一次使用 phpunit。

对现有 Writers 进行的所有单元测试都使用此逻辑:
- 创建文件。
- 使用相应的格式在文件中写入数据。
- 在 file_get_contents(filename).

上创建一个 assertEquals

所以,我写了这个测试:

public function setUp()
{
    $this->filename = 'formatedbool.xls';
    $this->sampleWriter = new XlsWriter($this->filename, false);
    $this->trueLabel = 'oui';
    $this->falseLabel = 'non';

    if (is_file($this->filename)) {
        unlink($this->filename);
    }
}

public function testValidDataFormat()
{
    $writer = new FormatedBoolWriter($this->sampleWriter, $this->trueLabel, $this->falseLabel);
    $writer->open();
    $writer->write(array('john', 'doe', false, true));
    $writer->close();

    $expected = '<html><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8" /><meta name=ProgId content=Excel.Sheet><meta name=Generator content="https://github.com/sonata-project/exporter"></head><body><table><tr><td>john</td><td>doe</td><td>non</td><td>oui</td></tr></table></body></html>';
    $this->assertEquals($expected, trim(file_get_contents($this->filename)));
}

当提交我的 PR 时,所有者说我:

just use a mock with expected method call and check calling argument, this will avoid creating the file. see https://phpunit.de/manual/current/en/test-doubles.html#test-doubles.mock-objects.examples.with-consecutive.php

我已开始使用 Mock 重写测试,但我在 file_get_contents 上遇到错误,因为未创建文件。

"write" 方法只是写入一个文件,return 什么都没有。

我想他希望我在转换 bool 之后,但在写入文件之前测试数据。 如何在不真正创建文件的情况下检查文件内容的结果? 或者只是在方法调用期间访问我的 $data ?

编辑感谢@Cerad,我提交的代码:

public function testValidDataFormat()
{
    $data = array('john', 'doe', false, true);
    $expected =  array('john', 'doe', 'no', 'yes');
    $mock = $this->getMockBuilder('Exporter\Writer\XlsWriter')
                   ->setConstructorArgs(array('formattedbool.xls', false))
                   ->getMock();
    $mock->expects($this->any())
           ->method('write')
           ->with($this->equalTo($expected));
    $writer = new FormattedBoolWriter($mock, $this->trueLabel, $this->falseLabel);
    $writer->open();
    $writer->write($data);
    $writer->close();
}

我正在等待项目所有者的回答。

EDIT PR 合并于 https://github.com/sonata-project/exporter/pull/56

@Cerad 通过对问题的评论回答了这个问题。

PR已被接受并合并,见https://github.com/sonata-project/exporter/pull/56