Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

ahmeda's avatar

How to make a test for image file?

I have this code to store a new post (it's work as testing manually)

public function store(PostRequest $request, Post $post)
{
    $data = $request->validated();
    
    $request->image->store('post_images');

    $data['image'] = $request->image->hashName();

    $post->create($data);

    return redirect()->route('posts.index');
}

My test:

/** @test */
public function an_admin_can_add_a_new_post()
{
    $admin = User::factory()->create(['is_admin' => true]);

    Storage::fake('public');

    $this->actingAs($admin)
        ->post(route('posts.store'), [
            'title' => 'how to write a clean code',
            'desc' => 'description of the post',
            'image' => $file = UploadedFile::fake()->image('post.jpg'),
            'tag_id' => Tag::factory()->create()->id,
        ]);

    Storage::assertExists('post_images/' . $file->hashName());

    $this->assertDatabaseCount('posts', 1);
}

The test is passed but I'm have feeling that this is not the correct way for testing image!

Please correct me if I'm wrong!

0 likes
8 replies
jlrdw's avatar

The testing of an upload would already be complete, Taylor tests framework features.

Or the Symfony team.

1 like
martinbean's avatar

The testing of an upload would already be complete, Taylor tests framework features.

The OP is clearly talking about testing the uploading of files in their application; not at the framework level.

martinbean's avatar

@rabeea Does the test pass? If so, it works.

As mentioned, it’s the example in the docs so yes, it’s the way to test file upload logic in your application.

1 like
jlrdw's avatar

@rabeea The point with file uploads is:

  • You can fake, assert, etc.

But to truly know if an upload works is to actually do some real uploads.

Laravel uses symfony components, which in turn uses php move. So if you code it correctly, it will work.

The problem is:

You can pass a test, which means you coded the test correctly.

But:

What if the real World code to upload isn't correct.

So:

A correctly coded test that works will have nothing to do, or won't fix incorrect real upload code.

Just my opinion, but I think testing an upload is a mute point. Go for "does it really work".

1 like
Tippin's avatar

I will add that upload tests work well not only for testing validation (http tests), but I like testing that my custom file service will stick a given file in the correct directory, along with renaming the file in the process.

But to your main point, I agree you still need to test "for real" to truly know your code does what it should when it comes to uploads.

1 like
ahmeda's avatar

That's a great point, thanks!

Please or to participate in this conversation.