加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 站长学院 > PHP教程 > 正文

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

发布时间:2020-12-13 22:24:40 所属栏目:PHP教程 来源:网络整理
导读:我正在为 sonata/exporter做贡献,这是一个用于多种格式(CSV,JSON,XML,XLS,…)的导出数据的库. 我在一个Writer上工作,通过封装另一个Writer(如CsvWriter或XlsWriter)将布尔值转换为字符串(例如,是/否). 这是我第一次使用phpunit. 在现有Writers上进行的所有单
我正在为 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)));
}

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

just use a mock with expected method call and check calling argument,this will avoid creating the file. see 07001

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

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

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

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

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读