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


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

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

我开发了一个Writer,它通过封装另一个Writer(如CsvWriter或XlsWriter)将布尔值转换为字符串(例如yes/no)。

这是我第一次使用phpunit。

对现有编写器进行的所有单元测试都使用此逻辑:
-创建一个文件
-使用相应的格式在文件中写入数据
-在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时,所有者告诉我:

只需将mock与预期的方法调用和check调用参数一起使用,就可以避免创建文件。看见https://phpunit.de/manual/current/en/test-doubles.html#test-doubles.mock-objects.examples.with-consective.php

我已经开始使用Mock重写测试,但我在file_get_contents上有一个错误,因为文件并没有创建。

"write"方法只是写入一个文件,不返回任何内容。

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

EDIT感谢@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();
}

我在等项目负责人的答复。

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

@Cerad通过对该问题的评论回答了此问题。

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