0

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?

2
  • How is your UserProvider? Like, how are you loading the routes on the provider? Commented Dec 23, 2024 at 18:49
  • That’s because you are trying to get route before initializing route name Commented Dec 23, 2024 at 22:59

1 Answer 1

-1

When you are trying to connect your Modules/User/Routes/api.php make sure you are using require instance of require_once

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.