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

发布时间:2022-04-30 发布网站:脚本宝典
脚本宝典收集整理的这篇文章主要介绍了PHPUnit测试一个写入文件并将内容检入已创建文件的函数脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在为 sonata/exporter做贡献,这是一个用于多种格式(CSV,JSON,XML,XLS,…)的导出数据的库.

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

这是我第一次使用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)));
}

提交我的公关时,业主说我:

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

“write”方法只是写入文件而不返回任何内容.

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

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

public function testValidDataFormat()
{
    $data = array('john',true);
    $expected =  array('john','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->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

脚本宝典总结

以上是脚本宝典为你收集整理的PHPUnit测试一个写入文件并将内容检入已创建文件的函数全部内容,希望文章能够帮你解决PHPUnit测试一个写入文件并将内容检入已创建文件的函数所遇到的问题。

如果觉得脚本宝典网站内容还不错,欢迎将脚本宝典推荐好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。