Laravel & phpunit 设置预期的 http 错误代码
Laravel & phpunit set expected http error code
我正在写一些测试。这是我的测试:
/** @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如果你需要任何其他文件,或者你可以问。
$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
行,并将 visit
更改为 get
似乎解决了我的问题
如果你想得到完整的响应对象,你可以使用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());
}
我正在写一些测试。这是我的测试:
/** @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如果你需要任何其他文件,或者你可以问。
$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
行,并将 visit
更改为 get
似乎解决了我的问题
如果你想得到完整的响应对象,你可以使用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());
}