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

cha*_*asr 5 php phpunit unit-testing symfony sonata

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

我在一个 Writer 上工作,它通过封装另一个 Writer(如 CsvWriter 或 XlsWriter)将布尔值转换为字符串(例如是/否)。

这是我第一次使用 phpunit。

在现有 Writer 上进行的所有单元测试都使用此逻辑:
- 创建一个文件。
- 使用相应的格式将数据写入文件。
- 做一个 assertEqualsfile_get_contents(filename)

所以,我写了这个测试:

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)));
}
Run Code Online (Sandbox Code Playgroud)

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

只需使用具有预期方法调用的模拟并检查调用参数,这将避免创建文件。见https://phpunit.de/manual/current/en/test-doubles.html#test-doubles.mock-objects.examples.with-consecutive.php

我已经开始使用 Mock 重写测试,但是我有一个错误 file_get_contents由于未创建文件而。

“write” 方法只是写入一个文件并且不返回任何内容。

我认为他希望我在转换 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();
}
Run Code Online (Sandbox Code Playgroud)

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

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

cha*_*asr -1

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

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