Reputation: 3179
I'm getting this error:
Expected status code 200 but received 404. Failed asserting that 200 is identical to 404.
When I try to call it from my Unit Test:
<?php
namespace Tests\Unit;
use App\Models\Project;
use Tests\TestCase;
class ExampleTest extends TestCase
{
public function testTakePlace()
{
$project = Project::factory()->make();
$response = $this->getJson('controllerUserProject_takePlace', [
'project_id' => $project->id,
]);
$response
->assertStatus(200)
->assertJsonPath([
'project.status' => Project::STATES['TO_BE_REPLIED'],
]);
}
}
However, controllerUserProject_takePlace
is correctly the name I gave to the route. Indeed, here is /routing/web.php
:
<?php
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\TestConnections;
use App\Http\Controllers\ControllerUserProject;
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/
Route::get('/controllerUserProject_takePlace/projects/{project_id}', [ControllerUserProject::class, 'takePlace'])->name('controllerUserProject_takePlace');
The controller ControllerUserProject
is correctly defined:
<?php
namespace App\Http\Controllers;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
class ControllerUserProject extends Controller
{
public function takePlace(Request $request, $project_id)
{
return [
'project_status' => Project::STATES['TO_BE_REPLIED']
];
}
}
Do you know why the use of the route returns 404 (not found)?
Upvotes: 0
Views: 1146
Reputation: 12845
Your route url is '/controllerUserProject_takePlace/projects/{project_id}'
while in the test you are using 'controllerUserProject_takePlace'
hence the 404 error.
Also the second parameter in getJson()
is array $headers so when you pass ['project_id' => $project->id]
it becomes second parameter taken as $headers.
You need to supply complete url to getJson('/controllerUserProject_takePlace/projects/' . $project->id);
or
Since you have already named your route you can use the route()
helper in getJson(route('controllerUserProject_takePlace', $project->id));
Change the url in your test
<?php
namespace Tests\Unit;
use App\Models\Project;
use Tests\TestCase;
class ExampleTest extends TestCase
{
public function testTakePlace()
{
$project = Project::factory()->make();
// $response = $this->getJson('/controllerUserProject_takePlace/projects/' . $project->id);
//Try using named route
$response = $this->getJson(route('controllerUserProject_takePlace', $project->id));
$response
->assertStatus(200)
->assertJsonPath([
'project.status' => Project::STATES['TO_BE_REPLIED'],
]);
}
}
Upvotes: 1