Laravel 5.2 | 测试UploadedFile在Post之后错过$ test值.错误?

sch*_*rht 22 phpunit file-upload laravel laravel-5 laravel-5.2

更新2016/04/26 11:30 GMT + 2解决方法

从Laravel 5.2.15开始,$ test参数被删除,但没有明确的原因,因为Symfony的UploadedFile仍然有$ test参数.

解决方法是暂时使用Laravel 5.2.14.

更新2016/04/26 11:00 GMT + 2

Laravel自己的UploadedFile没有传递$ test参数.查看这些资源:

我知道,还有另一个问题:如何在Laravel 5.2中测试文件上传,但标记的答案对我不起作用.

测试用例

我创建了一个Symfony的UploadedFile类的实例,我设置$testtrue.我将文件发布到file/upload.

class FileControllerTest extends TestCase
{
    use \Illuminate\Foundation\Testing\DatabaseTransactions;

    private $file;

    public function setUp()
    {
        parent::setUp();

        $this->file = new Symfony\Component\HttpFoundation\File\UploadedFile(
            public_path() . '/examples/example.jpg',
            'example.jpg',
            'image/jpeg',
            filesize(public_path() . '/examples/example.jpg'),
            null,
            true // for $test
        );
    }

    /** @test */
    public function it_uploads_a_valid_file()
    {
        var_dump($this->file); // $test = true
        $this->call('POST', 'file/upload', [], [], ['file' => $this->file],
            ['accept' => 'application/json']);

        $this->assertResponseOk();
    }
}
Run Code Online (Sandbox Code Playgroud)

调节器

namespace App\Http\Controllers;

class FileController extends Controller
{
    public function upload(Request $request)
    {
        var_dump($request->file('file')); // $test = false

        return [];
    }
}
Run Code Online (Sandbox Code Playgroud)

问题

  • 该文件后有争论true$test
  • 发布的文件到达 upload()
  • $request->file('file') 包含正确的参数,但是

    $ test假的

看来$ test的论点并没有超过后期调用.这是一个错误吗?

Mar*_*łek 30

说明

这真是有趣的事情.你在创建这篇文章时已经注意到了很多(如果有人有问题,应该仔细阅读).

在此提交中,您已经提到$testing参数已被删除,类的代码被简化,删除了反射以获取testing属性值Symfony\Component\HttpFoundation\File\UploadedFile.

现在最棘手的事情是,根据您正在测试的内容,您可能不会注意到更改并且一切都可能有效,但在某些情况下它不会,您将不会真正知道原因.

例如,一切都可能工作 - 文件将上传没有问题,但如果您添加到您的Request类实例mimes规则,如下所示:

'logo' => ['mimes:jpeg,png'],
Run Code Online (Sandbox Code Playgroud)

它将无法告诉你文件有无效的mime(这是因为在内部它也将被验证文件是否真的上传,如果测试实际上它与真正的上传不一样).

解决方案再次关注提交中真正改变的内容以及方法的外观.在此文件中,上传文件的实例返回如下:

 return $file instanceof static ? $file : new static(
            $file->getRealPath(), $file->getClientOriginalName(), $file->getClientMimeType(),
            $file->getClientSize(), $file->getError()
        );
Run Code Online (Sandbox Code Playgroud)

因此,如果文件是此类的实例,它将返回此实例未修改,否则它将创建now对象而不将$testing参数传递给类构造函数.

所以要解决这个问题,在测试文件上传时你不应该使用

\Symfony\Component\HttpFoundation\File\UploadedFile
Run Code Online (Sandbox Code Playgroud)

上课了.你现在应该使用

\Illuminate\Http\UploadedFile
Run Code Online (Sandbox Code Playgroud)

在测试文件上传时没有遇到任何奇怪的问题(当然你仍然应该将这个对象构造函数true作为$testing参数传递给它,现在它将在以后使用而没有问题)