在Laravel PHPUnit中测试未经授权的用户限制
Laravel版本5.2 在我的项目中,角色为_id=4的用户具有管理员角色,可以管理用户 我在AuthServiceProvider中定义了以下功能:在Laravel PHPUnit中测试未经授权的用户限制,php,unit-testing,laravel,phpunit,laravel-5.2,Php,Unit Testing,Laravel,Phpunit,Laravel 5.2,Laravel版本5.2 在我的项目中,角色为_id=4的用户具有管理员角色,可以管理用户 我在AuthServiceProvider中定义了以下功能: public function boot(GateContract $gate) { $this->registerPolicies($gate); $gate->define('can-manage-users', function ($user) { return $user->r
public function boot(GateContract $gate)
{
$this->registerPolicies($gate);
$gate->define('can-manage-users', function ($user)
{
return $user->role_id == 4;
});
}
我在UserController\uuu构造方法中使用了此功能,如下所示:
public function __construct()
{
$this->authorize('can-manage-users');
}
public function testNonAdminCannotManageUsers()
{
$user = Auth::loginUsingId(4);
$this->actingAs($user)
->visit('users')
->see('This action is unauthorized.');
}
在ExampleTest中,我创建了两个测试来检查定义的授权是否有效
角色为4的管理员用户的第一个测试。这个测试通过了
public function testAdminCanManageUsers()
{
$user = Auth::loginUsingId(1);
$this->actingAs($user)
->visit('users')
->assertResponseOk();
}
第二个测试针对的是另一个没有role_id=4的用户。我已尝试使用响应状态401和403。但测试失败了:
public function testNonAdminCannotManageUsers()
{
$user = Auth::loginUsingId(4);
$this->actingAs($user)
->visit('users')
->assertResponseStatus(403);
}
故障消息的前几行如下所示:
对[的请求失败。已收到状态代码[403]
C:\wamp\www\laravel\blog\vendor\laravel\framework\src\illumb\Foundation\Testing\Concerns\interacticswithpages.php:196
C:\wamp\www\laravel\blog\vendor\laravel\framework\src\illumb\Foundation\Testing\Concerns\interacticswithpages.php:80
C:\wamp\www\laravel\blog\vendor\laravel\framework\src\illumb\Foundation\Testing\Concerns\interacticswithpages.php:61
C:\wamp\www\laravel\blog\tests\ExampleTest.php:33
由异常“Illumb\Auth\Access\AuthorizationException”引起
在中显示消息“此操作未经授权。”
C:\wamp\www\laravel\blog\vendor\laravel\framework\src\illumb\Auth\Access\HandlesAuthorization.php:28
我还尝试使用“see”方法,如下所示:
public function __construct()
{
$this->authorize('can-manage-users');
}
public function testNonAdminCannotManageUsers()
{
$user = Auth::loginUsingId(4);
$this->actingAs($user)
->visit('users')
->see('This action is unauthorized.');
}
但是它也失败了。我做错了什么?我怎样才能通过测试?错误是调用
visit
方法。visit
方法在interactiveswithpages
特性中。此方法调用makeRequest
方法,该方法反过来调用assertPageLoaded
方法。此方法获得返回状态代码,如果它获取的代码不是200,它将捕获一个PHPUnitException
,并在消息中抛出一个HttpException
“对[{$uri}]的请求失败。收到状态代码[{$status}]”
这就是测试失败并显示上述消息的原因
可以使用get
方法而不是visit
方法成功通过测试。例如:
public function testNonAdminCannotManageUsers()
{
$user = App\User::where('role_id', '<>', 4)->first();
$this->actingAs($user)
->get('users')
->assertResponseStatus(403);
}
公共函数testNoAdminCannotManageUsers()
{
$user=App\user::where('role_id','',4)->first();
$this->actingAs($user)
->获取('用户')
->资产负债表(403);
}
此测试将通过并确认非管理员用户无法访问url。由于
Auth
中间件在默认情况下未经身份验证时重定向到登录路径,因此您还可以执行以下测试:
公共函数testNoAdminCannotManageUsers()
{
$user=Auth::loginUsingId(4);
$this->actingAs($user)
->访问('用户')
->assertRedirect(“登录”);
}
在这个问题上有什么进展吗?