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

Darival's avatar

Test Api 404 on multiple requests

Hi, I'm trying to test all the routes on my api but only the first request gets 200, all following requests get 404, but when I run any test individually (phpunit --filter test_something) they work.

<?php

class ProgramTest extends TestCase {

    /** @test */
    public function it_returns_index() {
        $this->get('api/v1/test')
             ->assertReturnOk(['limit' => 10]);
    }

    /** @test */
    public function it_returns_show() {
        $this->get('api/v1/test/12')
             ->seeJson(['id' => 12]);
    }
}
PHPUnit 4.8.23 by Sebastian Bergmann and contributors.
.F
Time: 2.33 seconds, Memory: 20.25Mb
There was 1 failure:
1) ProgramTest::it_returns_show
Invalid JSON was returned from the route. Perhaps an exception was thrown?
0 likes
3 replies
Darival's avatar
Darival
OP
Best Answer
Level 4

I've fixed this by changing the way I require my routes in routes.php from:

foreach (File::allFiles(__DIR__ . '/Routes') as $partial) {
    require_once $partial->getPathname();
}

to:

$phpunit = simplexml_load_file('phpunit.xml');

foreach (File::allFiles(__DIR__ . '/Routes') as $partial) {
    if ($phpunit->php->xpath('env[@name="APP_ENV"]')[0]['value'] == 'testing') {
        require $partial->getPathname();
    } else {
        require_once $partial->getPathname();
    }
}
2 likes
egarcia's avatar

You don't have to access phpunit's xpath because your TestCase class boots up with an application instance, so you already have access to App::environment() Facade or even better you have access to app()->environment() helper, so your code can be simpler like this:

foreach (File::allFiles(__DIR__ . '/Routes') as $partial) {
    if (app()->environment('testing')) {
        require $partial->getPathname();
    } else {
        require_once $partial->getPathname();
    }
}
2 likes
rasmuscnielsen's avatar

For anyone else out there coming across a similar issue, I found the problem for me was the order of custom middleware.

I had a custom middleware applying a global scope AFTER the "SubstitueBindings" middleware.

  • For the first HTTP call it returned the model (since the SubstiteBindings fetched the model before applying the custom scope)

  • For the second HTTP call returned 404 since the custom scope was now already applied in the previous request

Please or to participate in this conversation.