iT邦幫忙

2021 iThome 鐵人賽

DAY 7
1
Modern Web

每天一篇文章系列 第 7

07. DB x Factory x Test

昨天介紹過 Factory,今天我們要用在測試程式裡。

試一下建立三筆資料是否資料庫真的有三筆。

public function test_create_user()
{
    $users = User::factory()->count(3)->create();
    self::assertSame(3, count($users));
}

再試一下用 email 去查詢姓名,如果 factory 只需要一筆資料就不用 count(N)->create(),可以用 make()。

public function test_query_by_email()
{
    // 準備測試資料
    $user = User::factory()->make();
    $user->save();
    $expactedName = $user['name'];

    // 用 email 查詢姓名
    $email = $user['email'];
    $user = User::where( 'email', '=', $email )->firstOrFail();
    $actualName = $user->name;

    self::assertSame($expactedName,$actualName);
}

在測試檔案裡面加上 DatabaseTransactions,這樣就不會真的寫入資料了。

use Illuminate\Foundation\Testing\DatabaseTransactions;

class ExampleTest extends TestCase
{
    use DatabaseTransactions;
    ...

Database Testing

如果是測試資料庫內容,例如第一個測試是測試資料筆數,也可以用 assertDatabase。

$this->assertDatabaseCount('users', 3);

https://laravel.com/docs/8.x/database-testing#available-assertions

Eloquent ORM

常用的動作

函式 動作
create() create
save() update
destroy() delete
all() 讀取全部
findOrFail() 讀取第一筆,找不到會拋出例外
where() 條件查詢
count() 計算 collection 筆數

https://laravel.tw/docs/5.0/eloquent

Eloquent Collection

官方網站跟字典一樣有點可怕,可以用關鍵字 cheat sheet 或常用指令去找適合的教學。

https://laravel.com/docs/8.x/collections
https://laravel.com/docs/8.x/eloquent-collections

或看舊的文件
https://laravel.tw/docs/5.2/collections


上一篇
06. DB x tinker x seeder
下一篇
08. Laravel Sail x Xdebug x Coverage
系列文
每天一篇文章30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言