2016-09-27 80 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()); 
}