php - 下载文件的单元测试

标签 php unit-testing codeigniter phpunit

首先,我使用 codeigniter 作为我的 PHP 框架。很抱歉问这个,我正在尝试掌握单元测试的想法。他们说在开发站点功能之前进行单元测试是一个很好的做法。所以在这里我渴望学习:

我的方法:

function download()
{
    $data = file_get_contents("resources/temp/file.doc");
    $name = "new_file.doc";

    force_download($name, $data);
}

然后我用 testDownload 方法创建了一个测试 Controller :
public function testDownload()
{       
    //Call the controller method
    $this->CI->download();

    //Fetch the buffered output
    $out = output();

    $this->assertFalse(preg_match('/(error|notice)/i', $out));
}

然后我测试它: phpunit test.php 并给了我这个:
F[CIUnit] PHP Error: Warning - file_get_contents(resources/temp/file.doc): failed to open stream: No such file or directory File Path: controllers/contract.php (line: 22)


Time: 4 seconds, Memory: 7.50Mb

There was 1 failure:

1) ContractTest::testDownload
Failed asserting that 0 is false.

我只想测试它是否具有正确的路径。或者我真的需要一个测试脚本来下载文件吗?对不起,我只是糊涂了。

最佳答案

“没有这样的文件或目录”的原因:

当您使用 PHPUnit 进行测试时,当前工作目录将相对于您运行 phpunit 的目录。但是在代码中,您将相对于您的网络服务器目录进行写入。

顺便说一句,单元测试应该测试您编写的代码。在单元测试中测试外部资源似乎不是一个好主意。

关于php - 下载文件的单元测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11500724/

相关文章:

angularjs - 无法使用 mocha 测试指令范围

c# - 单元测试 TransactionScope 的使用

php - 使用日期时间的 NOW() 命令构建数组

php - CSS不想从另一个 Controller 上传

php - CodeIgniter:Try Catch 在模型类中不起作用

javascript - 如何使用动态 JS 变量解析 PHP 变量?

PHP搜索关键字

c# - Max()函数的测试用例设计

PHP-MYSQLI : dynamically select attributes from db and display in dropdown issues

php - 无法显示好友列表