昨天介绍过 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;
...
如果是测试资料库内容,例如第一个测试是测试资料笔数,也可以用 assertDatabase。
$this->assertDatabaseCount('users', 3);
https://laravel.com/docs/8.x/database-testing#available-assertions
常用的动作
函式 | 动作 |
---|---|
create() | create |
save() | update |
destroy() | delete |
all() | 读取全部 |
findOrFail() | 读取第一笔,找不到会抛出例外 |
where() | 条件查询 |
count() | 计算 collection 笔数 |
https://laravel.tw/docs/5.0/eloquent
官方网站跟字典一样有点可怕,可以用关键字 cheat sheet 或常用指令去找适合的教学。
https://laravel.com/docs/8.x/collections
https://laravel.com/docs/8.x/eloquent-collections
或看旧的文件
https://laravel.tw/docs/5.2/collections
>>: @Day22 | C# WixToolset + WPF 帅到不行的安装包 [建立基本的WPF框架]
课程目标 ‧ 了解Angular前端开发框架与其优势 ‧ 学会有效率的利用Angular开发前端网页...
ls 指令会列出目录中的各个档案与目录,供使用者浏览整个目录的结构,是个十分常用的指令。 但它的设计...
延续上一篇利用call back function Enumerate搜寻子目录下档案,今天再继续完...
今天要来介绍的是 NiFi Expression Language (以下简称NEL)。在前一篇我们...
上一次我们完成了 ContextMenu 的部分,ContextMenu 也有了属於自己的 View...