LoginSignup
7
6

More than 5 years have passed since last update.

Lumen(Laravel5), PHPUnitでファイルをPOST/アップロード

Posted at

はじめに

Larabel5のmicro-framework:LumenでREST API的なものを作ってUnitTest(PHPUnit)を書こうとしたときに、バイナリファイルをPOSTしようとした時にハマったので対策メモ。

前提

Laravel5抜粋
public function testPhotoCanBeUploaded()
{
    $this->visit('/upload')
         ->name('File Name', 'name')
         ->attach($absolutePathToFile, 'photo')
         ->press('Upload')
         ->see('Upload Successful!');
}

PHPUnit

ExampleTest.php
<?php

use Illuminate\Http\UploadedFile; // (1)

class FooTest extends TestCase
{
    public function testPostUpload()
    {
        $filepath =  '/tmp/image.jpg';

        // Illuminate\Http\UploadedFile
        $upfile = new UploadedFile(
                $filepath,             // file path
                'image.jpg',           // original Name
                'image/jpeg',          // mimeType
                filesize( $filepath ), // size
                null,                  // error
                true // (2)            // test
        );

        $response = $this->call( 
                'POST',                // method
                '/api/post',           // uri
                [ ],                   // parameters 
                [ ],                   // cookies 
                ['file' => $upfile ]   // files 
        );

        $this->assertJsonStringEqualsJsonString(
                $response->content(),
                json_encode( [
                    'result'  => true,
                    'message' => "Upload complete.",
        ] ) );
    }
}

(1) use Illuminate\Http\UploadedFile;

ファイルのアップロードをする方法を検索するとuse \Symfony\Component\HttpFoundation\File\UploadedFile;を使う記述がたくさん見つかる。でも、Laravel5/Lumenを使うなら、use Illuminate\Http\UploadedFile;を使ったほうが良いみたい。

参考

(2) UploadedFileの引数testをTrueにする

元になっているSymfonyのUploadedFileのtestパラメータの説明書きだと「Whether the test mode is active」となっていて、テストモードのときにActive(ture)にする必要があるみたい。(move()の動きを見ると、testパラメータにtrueが設定されていると、細かいチェックなしにファイルを移動させてる)

最後に

Laravel5/Lumenを調べてたら、Symfonyの中身を調べることになるとは思わなかった。

7
6
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
7
6