在单元测试中处理Symfony 2 UploadFile对象

时间:2015-06-01 23:28:08

标签: php file unit-testing symfony

我正在研究Symfony2项目。 我创建了一个简单的TempFile类来操作UploadFile。这是我的构造函数:

public function __construct(UploadedFile $file, $destination, $suffix)
{
    $this->file             = $file;
    $this->destination      = $destination;
    $this->fileId           = sprintf('%s_%s', uniqid(), (string) $suffix);
}

我的move方法

public function move()
{
    $extension = $this->file->guessExtension();
    if (!$extension) {
        throw new \Exception(__METHOD__ . ' -> Unable to detect extension');
    }

    $this->tmpFileName = sprintf('%s.%s', $this->fileId, $extension);
    $this->file->move($this->destination, $this->tmpFileName);
}

我尝试在我的测试中创建一个UploadFile对象,这就是我所做的:

protected function setUp()
{
    $this->file = tempnam(sys_get_temp_dir(), 'upload');
    imagepng(imagecreatetruecolor(10, 10), $this->file);
    $this->uploadedFile = new UploadedFile($this->file, "test.png");
}

public function testMoveWithAValidUploadedFile()
{
    $tempFile = new TempFile($this->uploadedFile, '/tmp', 'tmp');
    $tempFile->move();
    // Future assertion
}

我有以下错误:

Symfony\Component\HttpFoundation\File\Exception\FileException: The file "test.png" was not uploaded due to an unknown error

有什么想法吗?

THX, 此致

1 个答案:

答案 0 :(得分:1)

从内存中,Symfony2使用is_uploaded_file()检查文件是否作为请求的一部分上传。这可以使用UploadedFile类的测试模式覆盖。您还可以定义哪个PHP上载错误代码构成成功。

copy(__DIR__ . '/Fixtures/test.pdf', '/tmp/test.pdf');
new UploadedFile(
    '/tmp/test.pdf',
    'original.pdf',
    null,
    null,
    UPLOAD_ERR_OK,
    true /* test */
)