首页 > 解决方案 > 集成测试文件上传

问题描述

我目前正在开发一个具有某些表单功能的 MVC 网站。作为表单的一部分,用户可以选择上传文件。我已经为此编写了代码并且它运行良好,但我的问题来自于尝试编写自动化测试以确保我不会在未来的重构中破坏任何东西。

我已阅读有关文件上传的 laravel 文档并尝试复制此文件,但在断言文件存在时失败。该表格是可选的,但有一些数据需要与它一起发送。

测试文件

 public function testDirect_FormPassesWithFile() 
    {
        Storage::fake('local');
        $file = UploadedFile::fake()->create('document.pdf');
        $response = $this->post('/direct', $this->data());
        $response->assertSessionHasNoErrors();
        Storage::disk('local')->assertExists($file->hashName());
        $response->assertStatus(302);
        $this->assertCount(1, QuickQuote::all()); 
    }

 private function data() 
    { 
        return [
            'name' => $this->faker->name,
            'email' => $this->faker->email,
            'phone' =>'07718285557',
            'risk' => $this->faker->address,
            'rebuild' => $this->faker->numberBetween($min = 500000, $max = 1000000),
            'startdate' => '2019-09-01',
            'currentpremium' => $this->faker->numberBetween($min = 100, $max = 1000),
            'file' => 'document.pdf',
            '_token' => csrf_token()
        ];
    }

控制器


 public function store(StoreQuickQuote $request)
    {
        $validated = $request->validated();

        //Code entered if there are any files uploaded
        if ($request->file('file')) {
            //loop through each file and store, saving path to an array
            $files = array();
            foreach($request->file('file') as $file) {
                $path = $file->store('uploads'); 
                array_push($files, $path);
            }
            //Turn the array into json and then insert into the validated data
            $filenames = json_encode($files);
            $merged = array_merge($validated, ['file' => $filenames]);

            $quick_quote = QuickQuote::create($merged);
        }

        //No files so just store
        $quick_quote = QuickQuote::create($validated);

        return redirect('/direct')->with('success', 'Thanks! We\'ll Be In Touch.');
    }

验证请求

 public function rules()
    {
        return [
            'name' => 'required',
            'email' => 'required|email',
            'phone' => 'required',
            'risk' => 'required',
            'rebuild' => 'required',
            'startdate' => 'required',
            'currentpremium' => 'present',
            'file' => 'nullable'
        ];
    }

表单输入

<input type="file" id="file" name="file[]" multiple> 

我的输出总是

There was 1 failure:

1) Tests\Feature\DirectTest::testDirect_FormPassesWithFile
Unable to find a file at path [mJ4jQ2hmxW6uMMPEneUVS6O4bZziuuTT5kq2NFVS.pdf].
Failed asserting that false is true.

我不太确定我要去哪里,所以任何提示都会很棒。

谢谢

标签: phplaravelintegration-testing

解决方案


您在 POST 数据中将文件名作为字符串传递,但这是不正确的。您需要将文件本身发布到测试框架。您可以使用该call方法执行此操作。第 5 个参数用于发布的文件。

$this->call('POST', route('route.to.test'), $params, [], compact('file'))

推荐阅读