A Helpful Tip for your Laravel tests

Hey there.

If you're already using Laravel, I just want to share a very quick tip you can use to structure your test classes.

If you're a little clumsy with your nomenclature, when writing tests, you will often run into a stern warning from Composer:

Screenshot 2022-06-17 193515.png

Ouch.

We are facing this issue because the name of our class does not match the name of our PHP file. Our class is named "AnExampleTest" but the file itself is named "ExampleTest". We could also face this issue if the namespace does not match the folder structure.

Sure enough, fixing the file name and the namespace can solve the issue. However, I have found that a better way to declare such tests is to do so as anonymous classes. I was inspired to use this technique by observing the default migration files in Laravel 9.

So do something like this instead:

return new class extends TestCase
{
    /**
     * A basic test example.
     *
     * @return void
     */
    public function test_the_application_returns_a_successful_response()
    {
        $response = $this->get('/');

        $response->assertStatus(200);
    }
};

Since we do not need to import this class anywhere else, this should be a great fit for us.

That's all for now. Thank you for reading!