2016-08-19 35 views
2

我有一個簡單的文件上傳(圖片上傳),將圖片大小調整爲較小的一個。爲這個調整大小函數創建一個phpUnit測試,我需要一個代表圖像的模擬對象。如何爲圖像創建一個phpUnit測試?

是使用'testimage'還是有更好的方法?

+1

你有'class ImageResizeHelper'或類似的東西嗎? phpUnit是更多的類,但你仍然可以調用你的函數,把你的虛擬形象放入它,然後只聲明你期望的大小。 PHP有這樣的圖像大小:http://php.net/manual/ru/function.getimagesize.php – jaro1989

+0

@ jaro1989不,我使用$ _FILE變量,其中包含上傳的數據 –

+0

這個問題可能不是非常適合堆棧溢出,因爲什麼「最佳實踐」可能會導致主觀和斟酌的答案,而不是事實上的答案,因爲堆棧溢出社區首選 – Kmeixner

回答

2
<?php 
namespace tests\control; 

use SebastianBergmann\CodeCoverage\TestCase; 

class FileHandlerTest extends TestCase 
{ 
    /** 
    * @var array 
    */ 
    private $files = []; 

    /** 
    * Put your temp image into your filesystem. 
    * (Not good as unit tests must work with any system, 
    * but my research about mocking resources gave me nothing) 
    */ 
    protected function setUp() 
    { 
     if (file_exists(dirname(__FILE__) . '/testImage.jpg')) { 
      try { 
       rmdir(dirname(__FILE__) . '/testImage.jpg'); 
      } catch (\Exception $e) { 
       throw new \Exception('You have no permission to delete files in this directory:' . $e); 
      } 

     } else { 
      $image = imagecreate(500, 500); 
      try { 
       imagejpeg($image, dirname(__FILE__) . '/testImage.jpg'); 
      } catch (\Exception $e) { 
       throw new \Exception('You have no permission to create files in this directory:' . $e); 
      } 
     } 

     $this->files[] = '/testImage.jpg'; 
    } 

    public function testOperation() 
    { 
     $example = new \FileHandler($this->files, dirname(__FILE__)); 
     /** 
     * Set here all the variable inside your file, 
     * your code isn't working at this moment. 
     * Properties to set: uploadFolder, files 
     */ 
     $example->process(); 

     /** 
     * Get you new image from test dir here. 
     * It's yours TODO :p 
     */ 

     /** @var resource $newPicture */ 
     $size = getimagesize($newPicture); 

     /** 
     * also count it yourself, as I can't reproduce your code 
     */ 
     $this->assertEquals('200', $size[0]); 
     $this->assertEquals('200', $size[1]); 

    } 

    /** 
    * Deleting of test images. No try/catch here as it would fire on setup 
    */ 
    protected function tearDown() 
    { 
     if (file_exists(dirname(__FILE__) . '/testImage.jpeg')) { 
      rmdir(dirname(__FILE__) . '/testImage.jpeg'); 
     } 

     if (file_exists(dirname(__FILE__) . '/newImage.jpeg')) { 
      rmdir(dirname(__FILE__) . '/newImage.jpeg'); 
     } 
    } 
} 

您仍然需要做一些工作。我不想測試這樣的事情。 SetUp-method的評論就是關於它的。