How to test file upload in Laravel 5.2
When you create an instance of UploadedFile
set the last parameter $test
to true
.
$file = new UploadedFile($path, $name, filesize($path), 'image/png', null, true); ^^^^
Here is a quick example of a working test. It expects that you have a stub test.png
file in tests/stubs
folder.
class UploadTest extends TestCase{ public function test_upload_works() { $stub = __DIR__.'/stubs/test.png'; $name = str_random(8).'.png'; $path = sys_get_temp_dir().'/'.$name; copy($stub, $path); $file = new UploadedFile($path, $name, filesize($path), 'image/png', null, true); $response = $this->call('POST', '/upload', [], [], ['photo' => $file], ['Accept' => 'application/json']); $this->assertResponseOk(); $content = json_decode($response->getContent()); $this->assertObjectHasAttribute('name', $content); $uploaded = 'uploads'.DIRECTORY_SEPARATOR.$content->name; $this->assertFileExists(public_path($uploaded)); @unlink($uploaded); }}
➔ phpunit tests/UploadTest.phpPHPUnit 4.8.24 by Sebastian Bergmann and contributors..Time: 2.97 seconds, Memory: 14.00MbOK (1 test, 3 assertions)
In Laravel 5.4 you can also use \Illuminate\Http\UploadedFile::fake()
. A simple example below:
/** * @test */public function it_should_allow_to_upload_an_image_attachment(){ $this->post( action('AttachmentController@store'), ['file' => UploadedFile::fake()->image('file.png', 600, 600)] ); /** @var \App\Attachment $attachment */ $this->assertNotNull($attachment = Attachment::query()->first()); $this->assertFileExists($attachment->path()); @unlink($attachment->path());}
If you want to fake a different file type you can use
UploadedFile::fake()->create($name, $kilobytes = 0)
More information directly on Laravel Documentation.
I think this is the easiest way to do it
$file=UploadedFile::fake()->image('file.png', 600, 600)];$this->post(route("user.store"),["file" =>$file));$user= User::first();//check file exists in the directoryStorage::disk("local")->assertExists($user->file);
and I think the best way to delete uploaded files in the test is by using tearDownAfterClass static method,this will delete all uploaded files
use Illuminate\Filesystem\Filesystem;public static function tearDownAfterClass():void{ $file=new Filesystem; $file->cleanDirectory("storage/app/public/images");}