如何在PHPUnit中测试; 使用Laravel编写的API上传CSV文件?

Dev*_*arb 5 php csv phpunit unit-testing laravel

我想通过Laravel API上传CSV文件,然后使用PHPUnit测试上传.

store()在Controller和testCreate()函数中的功能基本上是什么样的.

这是我到目前为止所得到的:

<?php

use Illuminate\Foundation\Testing\DatabaseTransactions;
use Illuminate\Foundation\Testing\WithoutMiddleware;

class ProspectListControllerTest extends TestCase
{

use WithoutMiddleware, DatabaseTransactions;

public function testCreate()
{

    $file = new Symfony\Component\HttpFoundation\File\UploadedFile(storage_path('/crm/data/test-file.csv'), 'test-file.csv', 'text/plain', 446, null, true);

    $this->call('POST', '/api/lists-imports/', [], [], ['csv_file' => $file]);
    $this->dump()->assertResponseOk();
  }
}
Run Code Online (Sandbox Code Playgroud)

和控制器方法看起来像:

<?php

namespace App\Http\Controllers;

use App\ListImport;
use Illuminate\Http\Request;

class ListImportController extends Controller
{
public $model = ListImport::class;

public function store(Request $request, ListImport $importList)
{
    $request->file('importFile')->move(public_path('storage.crm.data'), $request->file('importFile')->getClientOriginalName());

    $importList->importFile = public_path('storage.crm.data') . '/' . $request->file('importFile')->getClientOriginalName();

    $importList->save();

}
}
Run Code Online (Sandbox Code Playgroud)

任何帮助将不胜感激 :)

Mat*_*mes 8

这是我的 Laravel 6 及更高版本功能测试的示例(“上传”是我的存储驱动程序):

    use Illuminate\Http\UploadedFile;

    Storage::fake('uploads');

    $header = 'Header 1,Header 2,Header 3';
    $row1 = 'value 1,value 2,value 3';
    $row2 = 'value 1,value 2,value 3';

    $content = implode("\n", [$header, $row1, $row2]);

    $inputs = [
        'csv_file' =>
            UploadedFile::
                fake()->
                createWithContent(
                    'test.csv',
                    $content
                )
    ];


    $response = $this->postJson(
        'file-upload',
        $inputs

    );

    $response->assertOk();
Run Code Online (Sandbox Code Playgroud)

  • 伟大的!`createWithContent()` 方法:Laravel v.6 文档中没有提及,但它被定义在 `Illuminate\Http\Testing\FileFactory` 类中。 (2认同)

小智 -2

Laravel 中有一种测试文件上传的新方法。https://laravel-news.com/testing-file-uploads-with-laravel

它是这样的:(来自文档)

   public function testAvatarUpload()
{
    Storage::fake('avatars');

    $response = $this->json('POST', '/avatar', [
        'avatar' => UploadedFile::fake()->image('avatar.jpg')
    ]);

    // Assert the file was stored...
    Storage::disk('avatars')->assertExists('avatar.jpg');

    // Assert a file does not exist...
    Storage::disk('avatars')->assertMissing('missing.jpg');
}
Run Code Online (Sandbox Code Playgroud)