我正在嘗試測驗我的 Laravel API,但在某些情況下,我提交了一個 post 請求,我收到了一個 401 錯誤,訊息“未經身份驗證”。所有受保護的 GET 請求都可以正確訪問,并且某些 POST 請求(如提交狀態)也運行良好。為什么我在某些情況下會收到 401 錯誤,而在其他情況下不會?
這是檔案
API 路由
Route::group(['middleware' => ['auth:sanctum']], function() {
Route::get('logout', [MantelAuthController::class, 'logout']);
Route::post('status', [MantelController::class, 'status']);
Route::post('deleteAccount', [MantelController::class, 'deleteAccount']);
});
登出測驗
public function test_logoutAPI()
{
$testEmail = getenv('TEST_EMAIL_API');
$testPassword = getenv('TEST_PASSWORD_API');
$response = $this->post('/api/login', [
'email' => $testEmail,
'password' => $testPassword
]);
$auth = $response->assertStatus(201)->decodeResponseJson()['token'];
$response = $this->get('/api/logout',
[
'Authorization' => "Bearer ".$auth
]);
$response->assertStatus(200);
}
發送狀態測驗
public function test_post_status()
{
$testEmail = getenv('TEST_EMAIL_API2');
$testPassword = getenv('TEST_PASSWORD_API');
// log in
$response = $this->post('/api/login', [
'email' => $testEmail,
'password' => $testPassword
]);
$auth = $response->assertStatus(201)->decodeResponseJson()['token'];
// get correct datetime
$response = $this->get('/api/getData',
[
'Authorization' => "Bearer ".$auth
]);
$date= $response->assertStatus(200)->decodeResponseJson()['date'];
// submit post request
$response = $this->post('/api/status',
[
'Authorization' => "Bearer ".$auth,
'status' => "secure",
'date' => $date
]);
$response->assertCreated();
}
洗掉賬戶測驗
public function test_delete_account()
{
$DeletedEmail = "[email protected]";
$DeletedPassword = "temporary";
$response = $this->post('/api/login', [
'email' => $DeletedEmail,
'password' => $DeletedPassword
]);
$auth = $response->assertStatus(201)->decodeResponseJson()['token'];
$response = $this->withHeaders(['Accept' => 'application/json'])
->post('/api/deleteAccount', [
'Authorization' => "Bearer ".$auth,
'password' => $DeletedPassword
]);
$response->assertSuccessful();
}
uj5u.com熱心網友回復:
您的部分問題是您混合了標題資料和發布資料。你應該嘗試使用withHeaders
https://laravel.com/docs/8.x/http-tests#customizing-request-headers
$response = $this->withHeaders([
'X-Header' => 'Value',
])->post('/user', ['name' => 'Sally']);
您也不必為每個測驗通過 API 路由請求實際登錄,因為這非常低效。您應該對您的登錄 API 路由進行測驗,但您應該訪問用戶模型并actingAs用于為其他請求設定身份驗證。
https://laravel.com/docs/5.2/testing#sessions-and-authentication
<?php
class ExampleTest extends TestCase
{
public function testApplication()
{
$user = factory(App\User::class)->create();
$this->actingAs($user)
->withSession(['foo' => 'bar'])
->visit('/')
->see('Hello, '.$user->name);
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/388227.html
標籤:php 拉拉维尔 测试 phpunit laravel-sanctum
上一篇:當微服務具有獨立的發布時間表時,端到端測驗的有效性?
下一篇:如何正確地從函式回傳
