Unit test for a file download?
after long thinking about this topic without a result, I hope someone can give me a hint about phpUnit-Test for downloads. How can I create a phpUnit test for this function, which execute a download for a zip-File? Or is there an oter usual practice to test a logic like this?
public function createOutput($zipFolderName) {
$zipFolderName = $zipFolderName."/imageResizer.zip";
header('Content-Type: application/zip');
header('Content-disposition: attachment; filename=' . $zipFolderName);
header('Content-Length: ' . filesize($zipFolderName));
readfile($zipFolderName);
}
I feel like there are a couple components to this function, and each part should be tested to make sure that it is being accomplished correctly:
$zipFolderName
path It looks like some sort of file handler abstraction could help you easily unit test this method.
class FileUtils {
public getDownloadFileName($folderName) {}
public getFileSize($file) {}
public readFile($file) {}
}
Now you could inject a file utility instance into your function. For your production code this class would delgate file operations to actual filesystem, BUT your test would provide a stub/mock allow you to make assertions that your unit is performing the actions expected.
public function createOutput($fileUtilsInstance, $zipFolderName) {
$zipFolderName = $fileUtilsInstance->getDownloadFileName($zipFolderName);
header('Content-Type: application/zip');
header('Content-disposition: attachment; filename=' . $zipFolderName);
header('Content-Length: ' . $fileUtilsInstance->getFilesize($zipFolderName));
$fileUtilsInstance->readFile($zipFolderName);
}
The same tactic could be applied to the header
method.
I suggest you vfsStream library:
vfsStream is a PHP stream wrapper for a virtual file system that may be helpful in unit tests to mock the real file system. It can be used with any unit test framework, like PHPUnit or SimpleTest.
Same useful info in:
Hope this help. Let me know if you need some examples
链接地址: http://www.djcxy.com/p/36050.html下一篇: 单元测试的文件下载?