Laravel 的功能测试 JSON API 在附加文件时失败并显示错误


Laravel's functional testing JSON API fails with an error when attaching files

所以我写了一个功能测试来测试上传功能,但它失败并出现以下错误:

1) UploadTest::testValidVideoUpload
Error: Call to a member function filter() on null
/.../vendor/laravel/framework/src/Illuminate/Foundation/Testing/Concerns/InteractsWithPages.php:765
/.../vendor/laravel/framework/src/Illuminate/Foundation/Testing/Concerns/InteractsWithPages.php:737
/.../vendor/laravel/framework/src/Illuminate/Foundation/Testing/Concerns/InteractsWithPages.php:718
/.../vendor/laravel/framework/src/Illuminate/Foundation/Testing/Concerns/InteractsWithPages.php:639
/.../tests/ShareTests/UploadTest.php:19

代码是:

public function testValidVideoUpload()
{
    $this->post(route('share.upload'), ['type' => 'video'])
        ->attach($this->test_case_files_path . 'testcase.mp4', 'file')
        ->seeJson(['error' => false]);
}

我正在使用:

  • 拉维尔 5.2 稳定版
  • phpUnit 5.2.2
  • PHP 7.0.3-2+deb.sury.org~trusty+1 ( cli) ( NTS )

编辑:

我正在 RESTful 服务上使用这些测试。我们可以为此使用attach方法吗???因为我查看了它的实现,它使用 DOM 解析器和 CSS 选择器来确定该输入名称是否真的存在于响应中!!!

这就是问题所在。显然(我还不确定,因为文档根本没有说明)在测试 JSON API 时不能使用 attach 方法。这就是我解决问题的方法。而不是

    $this->post(route('share.upload'), ['type' => 'video'],
        ['HTTP_Authorization' => "Bearer " . $token])
        ->attach($this->test_case_files_path . 'testcase.mp4', 'file')
        ->seeJson(['error' => false]);

我用了这个:

$uploadedFile = new 'Symfony'Component'HttpFoundation'File'UploadedFile(
            $file, 'testcase.mp4', 'video/mp4', filesize($file), null, true
        );
        $this->response = $this->call('post', route('share.upload'), ['type' => 'video'], [],
            ['file' => $uploadedFile],
            $this->transformHeadersToServerVars([
                'Authorization' => "Bearer " . $token,
                'Content-type' => 'multipart/form-data',
            ]));
        $this->seeJson(['error' => false]);