如何为图像创建phpUnit测试?

时间:2016-08-19 14:43:47

标签: php unit-testing phpunit

我有一个简单的文件上传(图片上传),可以将此图像调整为较小的图像。要为此resize函数创建一个phpUnit测试,我需要一个代表图像的模拟对象。

最佳做法是使用'testimage'还是有更好的方法?

1 个答案:

答案 0 :(得分: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的评论是关于它的。