spacedog4's avatar

How to show custom error message in laravel tests

I want to test if all the pages in my website are working, so I created an array with the routes in my admin page, go through the array and assert it status is equals to 200

But if it fails, it doesn't show me whitch page fails

...

class AdminTest extends TestCase {

    use RefreshDatabase;

    protected $main_pages = [
        '/admin/dashboard',
        '/admin/banners',
        '/admin/benefits',
        '/admin/plans',
        '/admin/installation-fees',
        '/admin/info-pages/a-doublenet',
        '/admin/info-pages/servicos',
        '/admin/informatives',
        '/admin/faqs',
        '/admin/contacts',
        '/admin/hires',
        '/admin/configs'
    ];
    
    ...

    public function test_loads_main_admin_pages()
    {
        Auth::login(factory('App\User')->create());

        foreach ($this->main_pages as $page) {
            $this->get($page)
                ->assertStatus(200);

            // Shows message: Unable to reach $page
        }
    }
}
0 likes
2 replies
tykus's avatar

Do not use the assertStatus method, instead use a generic assertion where you can specify the failure message:

foreach ($this->main_pages as $page) {
    $response = $this->get($page);

    \PHPUnit\Framework\Assert::assertTrue(
        $response->getStatusCode() === 200,
        "Unable to reach page: {$page}"
    );
}
2 likes
click's avatar
click
Best Answer
Level 35

Or you could wrap that all in your own little helper and add it to your own base test class.

Something like:

public function assertResponseStatus($response, $expectedHttpCode, $message = "Response status mismatch")
{
    $this->assertTrue(
        $response->getStatusCode() === $expectedHttpCode,
        $message
    );
}

And than you can use it in your test case like:

public function test_loads_main_admin_pages()
{
        Auth::login(factory('App\User')->create());

        foreach ($this->main_pages as $page) {
            $response = $this->get($page);

           $this->assertResponseStatus($response, 200, 'Unable to reach page: '. $page);
        }
}

You could even make your 'message' smarter by retrieving some values from the response so it automatically creates a useful error message. I can't test it right now but something like this:

Unexpected response from $response->getUrl(), expected $expectedHttpCode but got $response->getStatusCode()

1 like

Please or to participate in this conversation.