2016-09-27 84 views
1

我正在寫一些測試。下面是我的測試:Laravel&phpunit集預計http錯誤代碼

/** @test */ 
    public function a_normal_user_cannot_access_the_admin_panel() 
    { 
    // Note: This is a regular user, not an admin 
    $user = factory(User::class)->create(); 
    $this->actingAs($user); 
    $this->visit('/admin'); 

    // ???? 
    } 

在我MustBeAdministrator.php中間件:

public function handle($request, Closure $next) 
    { 
     $user = $request->user(); 

     if ($user && $user->isAdmin) { 
     return $next($request); 
     } 

     abort(403); 
    } 

當我訪問/admin,中間件與403錯誤中止。我怎樣才能斷言與phpunit的HTTP錯誤被拋出?我知道$this->setExpectedException(),但我無法讓它與http錯誤一起工作。我做錯了嗎?

注意:我對phpunit和異常都很陌生,所以很抱歉如果這是一個愚蠢的問題。如果您需要任何其他文件,或者您可以提問,這裏是repo for this project

+0

嘿,你可以發佈對自己的問題的答案,這不是被禁止:) – iScrE4m

+0

@ iScrE4m我沒有回答,但是不會讓我接受它作爲2天的答案:(我會接受它。 –

+0

哦,對不起,我沒有沒有通知,所以沒有在評論中顯示我:) – iScrE4m

回答

1
$user = factory(User::class)->create(); 
$this->actingAs($user); 
$this->setExpectedException('Symfony\Component\HttpKernel\Exception\HttpException'); 
$this->get('/admin'); 
throw $this->response->exception; 

Found this article。添加setExpectedException線,該throw線,並改變visitget似乎解決我的問題

+0

請將您的答案標記爲正確答案。 –

+1

@MihkelAllorg所以SO不會讓我再接受2個小時。那我會。 –

0

,如果你想獲得完整的響應對象,你可以使用call方法

/** @test */ 
public function a_normal_user_cannot_access_the_admin_panel() 
{ 
    // Note: This is a regular user, not an admin 
    $user = factory(User::class)->create(); 
    $this->actingAs($user); 
    $response = $this->call('GET', '/admin'); 

    $this->assert(403, $response->status()); 
}