测试
HTTP 功能测试
在应用程序中执行 HTTP 功能测试 时,通常需要确保已登录以检查安全性,或仅访问受保护的位置。Shield 提供了 AuthenticationTesting
特性来帮助您。在测试类中使用它,然后可以使用获取 User 实例的 actingAs()
方法。此用户将在测试期间登录。
<?php
use CodeIgniter\Shield\Test\AuthenticationTesting;
use Tests\Support\TestCase;
use CodeIgniter\Shield\Authentication\Actions\Email2FA;
class ActionsTest extends TestCase
{
use DatabaseTestTrait;
use FeatureTestTrait;
use AuthenticationTesting;
public function testEmail2FAShow()
{
$result = $this->actingAs($this->user)
->withSession([
'auth_action' => Email2FA::class,
])->get('/auth/a/show');
$result->assertStatus(200);
// Should auto-populate in the form
$result->assertSee($this->user->email);
}
}
提高运行测试的速度
由于密码的安全性更高,因此 Shield 默认将 Config\Auth::$hashCost = 12
设置为 12。但是,为了增加测试执行时间,我们已将测试环境的 $hashCost = 4
设置为 4。
如果您在项目中使用 Shield 且测试执行时间较长,只需在项目的 phpunit.xml.dist 文件中将 $hashCost = 4
设置为 4,如下所示
<php>
<!-- Set hashCost for improving the speed of running tests -->
<env name="auth.hashCost" value="4"/>
</php>