在 Laravel 中测试文件上传

我正在使用带有 Dropzone.js 的 Laravel 5.8 将文件上传到库,我能够成功地做到这一点。我认为编写一个测试来验证这一点是一种很好的做法,但它总是失败。

我的控制器方法看起来像刚刚被调用store,它看起来像这样:


/**

 * Store a new library file in the database

 *

 * @param StoreArticle $request

 * @return void

 */

public function store(StoreLibrary $request)

{

    $data = $request->validated();


    $category = $data['category'];


    $files = $data['file'];


    foreach ($files as $file) {

        $original_name = $file->getClientOriginalName();

        $mime_type = $file->getClientOriginalExtension();

        $size = $file->getSize();


        // Generate a name for this file 

        $system_generated_name = sha1(date('YmdHis') . str_random(30)) . '.' . $file->getClientOriginalExtension();


        // Store the file on the disk 'library'

        $path = Storage::disk('library')->putFileAs(null, $file, $system_generated_name);


        // Store a reference to this file in the database

        Library::create([

            'display_name' => $original_name,

            'file_name' => $system_generated_name,

            'mime_type' => $mime_type,

            'size' => $size,

            'disk' => $this->disk,

            'storage_location' => $path,

            'category' => $category,

        ]);

    }


    // Return a JSON response

    return response()->json([

        'success' => true,

        'file' => [

            'original_name' => $original_name,

            'generated_name' => $system_generated_name,

            'path' => $path,

            'size' => $size,

        ]

    ], 200);

}


幕布斯7119047
浏览 152回答 1
1回答

小怪兽爱吃肉

我设法找到了解决此问题的方法。这是因为file是一个数组,这意味着它在测试时需要有键和索引。这显示在下面的代码中:/** @test */public function a_user_with_permission_can_add_files_to_the_library(){    $this->withoutExceptionHandling();    Storage::fake('library');    $this->setupPermissions();    $user = factory(User::class)->create();    $user->assignRole('admin');    // Assert the uploading an image returns a 200 response    $this->actingAs($user)        ->post(route('admin.library.store'), [            'category' => 'Some category',            'file' => [                0 => UploadedFile::fake()->create("test.jpg", 100),                1 => UploadedFile::fake()->create("test.png", 100),                2 => UploadedFile::fake()->create("test.doc", 100),                3 => UploadedFile::fake()->create("test.ppt", 100),                4 => UploadedFile::fake()->create("test.pdf", 100),            ]        ])->assertStatus(200);    $this->assertEquals(5, Library::count());}
打开App,查看更多内容
随时随地看视频慕课网APP