I'm new to working on backend to make a unit testing of index method with Bearer Token for authentication.
But, I got failure after I run the command : .\vendor\bin\phpunit
like below :
PHPUnit 9.5.27 by Sebastian Bergmann and contributors.
..F 3 / 3 (100%)
Time: 00:00.228, Memory: 24.00 MB
There was 1 failure:
1) Tests\Feature\UserControllerTest::test_returns_user_data_list_successfully
Expected response status code [200] but received 404.
The following errors occurred during the request:
{
"success": false,
"message": "Failed",
"error_code": 4041,
"errors": {
"message": "Data not found"
}
}
Failed asserting that 200 is identical to 404.
C:\Users\artha\Documents\Switch\vendor\laravel\framework\src\Illuminate\Testing\TestResponse.php:177
C:\Users\artha\Documents\Switch\tests\Feature\UserControllerTest.php:18
For UserContoller.php :
class UserController extends Controller
{
public function __construct()
{
$this->middleware('auth.jwt');
}
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
$user = User::orderBy('created_at', 'DESC')->all();
$message = 'Success';
return $this->sendResponse($user->makeVisible('role'), $message, 200);
}
}
The code of route/api.php
:
Route::resource('user', UserController::class, ['except' => ['create', 'edit']]);
And I made UserContollerTest.php
like below :
<?php
namespace Tests\Feature;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Foundation\Testing\WithFaker;
use Tests\TestCase;
class UserControllerTest extends TestCase
{
public function test_returns_user_data_list_successfully()
{
$token = 'eyJ0eXA.....dY3CtVO1T4o--8nM';
$response = $this->withHeaders(['Authorization' => 'Bearer '. $token,
'Accept' => 'application/json'])
->get('api/user/index');
$response->assertStatus(200);
}
}
I tried to solved with various ways on internet like read all official documentations and others but I didn't get insight right to solve this. I made .env.testing
, too.
Any idea, how to solving this problem?
Thank you for your insight.
I tried to solve with these link : https://stackoverflow.com/questions/46769959/laravel-phpunit-test-with-api-token-authentication
https://laravel.com/docs/6.x/http-tests#session-and-authentication