PHPUnit:assertFileEquals()失败

Mir*_*iai 5 php phpunit

我正在开发一个PHP软件,可以从图像创建缩略图.

现在我需要确保成功创建缩略图,换句话说,初始图像已经正确调整大小/裁剪.

我认为只有一种方法可以做到这一点:我手动创建缩略图以与软件创建的缩略图进行比较.

但是怎么测试?

如果我assertFileEquals()用来比较我创建的缩略图和软件创建的缩略图,当然测试失败,即使两个图像相同.

我想,只要因为两个文件的创建日期不同或出于类似原因而发生这种情况.

那么,该怎么办?

BVe*_*rov 4

存储一对source.pngexpected_result.png(由软件生成一次,验证良好并存储为参考图像)就足够了。实现比较函数似乎是一种开销。

单元测试的主要目的是在系统行为发生变化时发出信号,如果新创建的缩略图与参考缩略图不匹配,这就是此类测试要做的事情。

然而,如果由于某种原因软件每次生成的图像略有不同,那么,如果这不是错误,请使用建议的比较相似图像方法。

如果图像内容不同怎么办

对于本示例中使用的 PNG 文件,其内容可能包含一些辅助信息,例如 EXIF

因此,您可能必须尝试创建没有此附加信息的副本图像。请验证以下代码是否适合您:

public function testThumbnails()
{
    $this->assertPngImageContentsEquals(__DIR__ . '/test1.png', __DIR__ . '/test2.png');
}

public static function assertPngImageContentsEquals(
    $expected,
    $actual,
    $message = 'Contents of PNG files differ'
)
{
    self::assertFileExists($expected, $message);
    self::assertFileExists($actual, $message);

    $copy_expected = self::_makePngCopy($expected, __DIR__ . '/expected.png');
    $copy_actual = self::_makePngCopy($actual, __DIR__ . '/actual.png');

    var_dump($copy_expected);
    var_dump($copy_actual);

    self::assertFileEquals($copy_expected, $copy_actual, 'Thumbnails differ');

    unlink($copy_expected);
    unlink($copy_actual);
}

private static function _makePngCopy($sourceFile, $resultFile)
{
    $image = imagecreatefrompng($sourceFile);
    imagepng($image, $resultFile);
    imagedestroy($image);
    return $resultFile;
}
Run Code Online (Sandbox Code Playgroud)