I am developing a modular project in Laravel 11, where each module defines its routes inside itself. The routes are working perfectly in the browser and Postman, but when testing the same routes using PHPUnit, they are not found.
For example, this is my test case:
<?php
namespace Tests\Feature\User;
use Illuminate\Support\Facades\Route;
use Modules\User\App\Models\User;
use Tests\TestCase;
class UserTest extends TestCase
{
protected function setUp(): void
{
parent::setUp();
$this->withoutMiddleware();
$this->artisan('route:clear');
// Debugging route loading
dd(Route::getRoutes()->getByName('user.otp')); // This returns null in the test environment
}
public function test_send_otp()
{
$randomNumber = '0915' . rand(0000000, 9999999);
$response = $this->postJson(route('user.otp'), [
'mobile' => $randomNumber,
]);
$response->assertStatus(200);
}
}
Here’s how the route is defined in the module (Modules/User/Routes/api.php):
<?php
use Illuminate\Support\Facades\Route;
Route::prefix('user')->group(function () {
Route::post('/send-otp',\Modules\User\App\Http\Controllers\SendOtpController::class)->name('user.otp');
});
When running php artisan route:list, I can see the user.otp route is correctly defined and accessible.
However, when I try to test it using PHPUnit, I get the following error:
Route [user.otp] not defined.
What I've Tried:
Clearing caches with php artisan route:clear and php artisan config:clear. Adding \Modules\User\Providers\UserProvider manually in the setUp() method:
$this->app->register(\Modules\User\Providers\UserProvider::class);
Debugging route definitions using Route::getRoutes()->getIterator() in the test environment, which does not show the user.otp route.
Any guidance or solution to this problem is much appreciated. Thanks
Question: Why are the routes not loading in the test environment, and how can I ensure the module routes are properly registered during tests?
UserProvider? Like, how are you loading the routes on the provider?