在代码中将文件发送到Restful服务

Mar*_*łek 4 testing rest laravel codeception laravel-5

我想测试文件上传的restful API测试.

我试着跑:

 $I->sendPOST($this->endpoint, $postData, ['file' => 'example.jpg']);
Run Code Online (Sandbox Code Playgroud)

我希望它的行为与example.jpg文件输入中的用户发送文件的行为相同,file但它似乎没有这种方式.我越来越:

[PHPUnit_Framework_ExceptionWrapper]上传的文件必须是UploadedFile的数组或实例.

是否可以在代码中使用REST插件上传文件?文档非常有限,很难说如何做到这一点.

我也在使用Postman插件测试API Google Chrome,我可以使用这个插件上传文件而没有问题.

Yar*_*ius 10

我最近在解决同样的问题时遇到了问题,并且发现在不使用Symfony的UploadedFile类的情况下还有另一种解决问题的方法.您只需要使用与$ _FILES数组相同的格式传递带有文件数据的数组.例如,这段代码非常适合我:

$I->sendPOST(
    '/my-awesome-api',
    [
        'sample-field' => 'sample-value',
    ],
    [
        'myFile' => [
            'name' => 'myFile.jpg',
            'type' => 'image/jpeg',
            'error' => UPLOAD_ERR_OK,
            'size' => filesize(codecept_data_dir('myFile.jpg')),
            'tmp_name' => codecept_data_dir('myFile.jpg'),
        ]
    ]
);
Run Code Online (Sandbox Code Playgroud)

希望这可以帮助某人并阻止检查框架的源代码(我被迫做了,因为文档跳过了这么重要的细节)


Mar*_*łek 3

经过测试似乎可以正常工作,我们需要使用UploadedFile对象作为文件。

例如:

$path = codecept_data_dir();
$filename = 'example-image.jpg';

// copy original test file to have at the same place after test
copy($path . 'example.jpg', $path . $filename);

$mime = 'image/jpeg';

$uploadedFile = new \Symfony\Component\HttpFoundation\File\UploadedFile($path . $filename, $filename, $mime,
    filesize($path . $filename));

$I->sendPOST($this->endpoint, $postData, ['file' => $uploadedFile]);
Run Code Online (Sandbox Code Playgroud)