簡體   English   中英

Laravel phpunit 測試授權失敗

[英]Laravel phpunit test failing authorization

我有一個有效的api應用程序。

我需要寫一個測試決定使用laravel的phpunit測試。 這個簡單的應用程序只允許經過身份驗證的用戶可以storeupdatedeletebook 其他所有人(無論是否經過身份驗證)都可以檢索所有books的列表或查看一book的詳細信息。

對於我的books測試,我編寫了一個測試,它首先創建一個user ,然后為該用戶創建一個隨機token 然后在發布新書記錄時使用withHeaders傳遞令牌

class BooksTest extends TestCase
{
    public function test_onlyAuthenticatedUserCanAddBookSuccessfully()
    {
        $user = factory(User::class)->create();
        $token = str_random(10);
        $book = factory(Book::class)->create();

        $response = $this->withHeaders(['Authorization' => "Bearer $token"])
            ->json('POST', '/api/books', [
                'title' => 'book post',
                'author' => 'post author'
            ]);

        $response->assertStatus(201);
    }
}

這里我使用默認的 Laravel 5.6 UserFactory和我自己的BookFactory

$factory->define(Book::class, function (Faker $faker) {
    return [
        'title'     => $faker->sentence,
        'author'    => $faker->name,
        'user_id'   => 1
    ];
});

$factory->define(Rating::class, function (Faker $faker) {
    return [
        'user_id'   => 1,
        'book_id'   => mt_rand(1, 2),
        'rating'   => mt_rand(1, 5)
    ];
});

當我運行測試時,它失敗了,我得到401而不是200 ,這意味着用戶未經授權。

我有一種感覺,我可能沒有在我的測試中正確設置$user以在POST期間使用,但我不確定並且真的需要幫助才能正確設置。

您可以在json()方法的第四個參數中發送標頭,如下所示:

$response = $this->json('POST', '/api/books', [
            'title' => 'book post',
            'author' => 'post author'
        ],['Authorization' => "Bearer $token"]);

由於json方法本身具有傳遞標頭的條件

或者您可以使用post()方法作為

 $response = $this->post('/api/books', [
            'title' => 'book post',
            'author' => 'post author'
        ],['Authorization' => "Bearer $token"]);

嘗試這樣,希望可以解決您的問題

不確定身份驗證是如何掛在您的應用程序上的,但是您可以嘗試這樣做:

...

$this->actingAs($user)
    ->jsonPost('/api/books', [
        // ...  
    ]);

$response->assertStatus(201);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM