➔ phpunit tests/UploadTest.php
PHPUnit 4.8.24 by Sebastian Bergmann and contributors.
.
Time: 2.97 seconds, Memory: 14.00Mb
OK (1 test, 3 assertions)
Das sollte funktionieren, tut es aber nicht. $request->file('photo') hat zwar das UploadFile-Objekt, aber $test in diesem Objekt hat seinen Standardwert false. Seltsam, weil die neue UploadedFile den Parameter $test = true hat.
– schellingerht
25. April 2016 um 21:04 Uhr
Die obige Antwort reicht für > 5.2.14 nicht aus. Die richtige Antwort finden Sie hier: stackoverflow.com/questions/36857800/…
– schellingerht
18. Mai 2016 um 18:40 Uhr
Es sollte sein $file = new UploadedFile($path, $name, 'image/png', filesize($path), null, true);
– Hanson
5. März 2017 um 3:50 Uhr
Zum Symfony 4.1 die richtige Implementierung ist $file = new UploadedFile($path, $name, 'image/png', null, true);
– Fanan Dala
4. September 2020 um 12:52 Uhr
Alessandro Benoit
In Laravel 5.4 können Sie auch verwenden \Illuminate\Http\UploadedFile::fake(). Ein einfaches Beispiel unten:
Aber die Methode create() besteht die Validierung nicht, wenn Sie nur einen bestimmten MIME-Typ wie mp3 fragen…
– Syl
26. Juli 2017 um 11:30 Uhr
Mahdi mehrabi
Ich denke, das ist der einfachste Weg, es zu tun
$file=UploadedFile::fake()->image('file.png', 600, 600)]; $this->post(route("user.store"),["file" =>$file));
$user= User::first();
//check file exists in the directory
Storage::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");
}
The laravel documentation has an answer for when you want to test a fake file. When you want to test using a real file in laravel 6 you can do the following:
namespace Tests\Feature;
use Illuminate\Http\UploadedFile;
use Tests\TestCase;
class UploadsTest extends TestCase
{
// This authenticates a user, useful for authenticated routes
public function setUp(): void
{
parent::setUp();
$user = User::first();
$this->actingAs($user);
}
public function testUploadFile()
{
$name="file.xlsx";
$path="absolute_directory_of_file/" . $name;
$file = new UploadedFile($path, $name, 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', null, true);
$route="route_for_upload";
// Params contains any post parameters
$params = []; $response = $this->call('POST', $route, $params, [], ['upload' => $file]); $response->assertStatus(200); } }
Laravels Dokumentation (5.8) zum Fälschen von Datei-Uploads: laravel.com/docs/5.8/http-tests#testing-file-uploads
– Seelenaufsteiger
26. April 2019 um 21:36 Uhr