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

时间:2016-02-09 07:42:48

标签: php laravel-5 phpunit functional-testing laravel-5.2

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

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]);
}

我正在使用:

  • Laravel 5.2 Stable
  • phpUnit 5.2.2
  • PHP 7.0.3-2 + deb.sury.org~trusty + 1(cli)(NTS)

编辑:

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

1 个答案:

答案 0 :(得分:0)

这是问题所在。显然(我还不确定,因为文档根本没有说明),在测试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]);