假设我有一组由中间件保护的路由:
Route::group(['middleware' => 'verified'], function () {
Route::get('/profile', 'ProfileController@show')->name('profile.show');
Route::get('/settings', 'SettingsController@show')->name('settings.show');
});
如何测试这些路由是否受verified
中间件的保护?如果我写这些测试,它们被认为是功能测试还是单元测试?
中间件测试在很大程度上取决于中间件本身的逻辑和可能的结果。让我们以您引用的verified
中间件为例:
如果用户没有验证他的电子邮件(email_verified_at
属性为null(,我们希望用户被重定向(302(到"验证您的电子邮件"页面,否则我们希望得到正常响应(200(。
我们如何模拟用户访问我们的页面?采用CCD_ 4方法。来自文档:
actingAs
助手方法提供了一种简单的方法,可以将给定用户验证为当前用户。
所以我们的代码看起来像这样:
use AppUser;
class ExampleTest extends TestCase
{
public function testAccessWithoutVerification()
{
// Create a dummy user
$user = factory(User::class)->create();
// Try to access the page
$response = $this->actingAs($user)
->get('/the-page-we-want-to-test');
// Assert the expected response status
$response->assertStatus(302);
}
public function testAccessWithVerification()
{
// Create a dummy user, but this time we set the email_verified_at
$user = factory(User::class)->create([
'email_verified_at' => CarbonCarbon::now(),
]);
// Try to access the page
$response = $this->actingAs($user)
->get('/the-page-we-want-to-test');
// Assert the expected response status
$response->assertStatus(200);
}
}
文档中有一整页专门介绍HTTP测试,请查看。