When writing tests in Laravel, the simplest way to simulate a file upload is by using the UploadedFile::fake()
helper:
$file = UploadedFile::fake()->image('avatar.png');
$mediaResponse = post('/api/user_media/upload', ['media' => $file])->assertStatus(200)
This works well for basic scenarios, but sometimes we need to test with real files—such as oversized images or files with invalid content—to verify how our application handles them.
To upload a specific file stored in your test directory, you can create an UploadedFile
instance manually:
// UploadedFile will move the file
Storage::copy('test/mail-test.docx', 'tmp/mail-test.docx');
$filename = 'too-large.png';
$uploadedFile = new UploadedFile(
storage_path("app/private/tmp/$filename"),
$filename,
test: true,
);
This approach allows you to use an actual file from your storage for more realistic and edge-case testing.
Top comments (0)