Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a PHP-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);
    }
like image 935
michael-mammut Avatar asked Aug 28 '16 18:08

michael-mammut


1 Answers

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:

  • builds the correct $zipFolderName path
  • sets the correct headers
  • calculates the correct filesize
  • reads the file

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.

like image 114
dm03514 Avatar answered Nov 11 '22 19:11

dm03514