php - 如何为图像创建 phpUnit 测试?

标签 php unit-testing phpunit

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

使用“测试图像”是最佳实践还是有更好的方法?

最佳答案

<?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 的评论就是关于它的。

关于php - 如何为图像创建 phpUnit 测试?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39041876/

相关文章:

php - 如何将 css 应用于 src 为 PHP 的 iframe?

php - 在 Zend 1.11.2 中运行的应用程序在 1.12.1 中不起作用

c# - 如何通过安全地签署公共(public) token key 来使 InternalsVisibleTo 属性起作用?

node.js - 我收到错误,无法使用 mocha 找到模块 './--require.js'

php - 使用 TDD 创建报告

php - Mysql 模块未在 phpinfo() 中加载;

iOS - UIViewController 中的依赖注入(inject)

laravel - 方法 Illuminate\Auth\RequestGuard::logout 不存在 Laravel Passport

phpunit - 在所有测试之前运行命令

php - 如何更新一个sql db