今天就讓我們依照前一天的情境題,來撰寫測試案例函數吧!
這次同樣地,先讓我們規畫擬訂測試案例:
使用者註冊:
請求錯誤的驗證連結:
話不多說,來寫 Code !
<?php
namespace Tests\Feature;
use App\Mail\VerifyUserMail;
use App\Models\User;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Foundation\Testing\WithFaker;
use Illuminate\Support\Facades\Mail;
use Tests\TestCase;
class UserControllerTest extends TestCase{
use WithFaker;
use RefreshDatabase;
public function testRegisterAndVerifySuccess() {
Mail::fake();
$data = [
'name' => $this->faker->name,
'email' => $this->faker->email,
'password' => $this->faker->password,
]; $response = $this->post(route('register'), $data);
$response->assertOk();
$this->assertDatabaseHas('users', [
'email' => $data['email'],
]); $verifyLink = null;
$userId = null;
Mail::assertSent(VerifyUserMail::class, function ($mail) use (&$verifyLink, &$userId) {
$user = User::first();
$userId = $user->id;
$token = $user->verify_email_token;
$mail->build();
$viewData = $mail->viewData;
$verifyLink = route('verify-user-email', ['token' => $token]);
$assertRecipient = $mail->hasTo($user->email);
$assertVerifyLink = isset($viewData['verifyLink']) &&
$viewData['verifyLink'] === $verifyLink;
return $assertRecipient && $assertVerifyLink;
}); $response = $this->get($verifyLink);
$response->assertOk();
$this->assertDatabaseMissing('users', [
'id' => $userId,
'email_verified_at' => null,
]); } public function testVerifyFailedWhenGotWrongLink() {
$user = User::factory()->create();
$token = $user->verify_email_token . 'x';
$verifyLink = route('verify-user-email', ['token' => $token]);
$response = $this->get($verifyLink);
$response->assertNotFound();
$this->assertDatabaseHas('users', [
'id' => $user->id,
'email_verified_at' => null,
]); }}
在以上程式碼中,我們實作了以下測試案例函數:
testRegisterAndVerifySuccess()
在這個測試案例函數中,我們驗證了完整的驗證流程,從使用者送出註冊資料、系統建立使用者資料並寄出驗證信、使用者點選驗證連結、更新使用者驗證時間等。
testVerifyFailedWhenGotWrongLink()
在這個測試案例函數中,我們驗證了當不正確的驗證連結被請求時,將不會讓使用者的驗證狀態轉變為已驗證。
以上就是今天的練習,希望對大家有所幫助。
下一篇讓我們探討多重資料庫連線的情境吧!
如果您喜歡這篇文章,歡迎加入追蹤以接收新文章通知 😄