前言
实现一个博客的侧边栏的链接,然后顺便对其进行单元测试的过程。
Archives
一、视图中展示SQL结果
- 一条 sql 语句【查询】
select
year(created_at) year,
monthname(created_at) month,
count(*) published
from posts
group by year, month
order by created_at desc
- 对应的 ORM语句【测试】
$ php artisan tinker
App\Post::selectRaw('year(created_at) year, monthname(created_at) month, count(*) published')
->groupBy('year', 'month')
->get()
->toArray();
- 侧边栏链接的'视图'【展示】
<ol class="list-unstyled">
@foreach ($Archives as $stats)
<li>
<a href="#">{{ $stats['month'] }}</a>
</li>
@endforeach
</ol>
以上可以通过URL中的参数触发。
- URL中的时间参数解析【触发】
if ($month = request('month')) {
$posts->whereMonth('created_at', Carbon::parse($month)->month);
}
Ref: Laravel Carbon函数
也可以选择year和month一并解析,然后直接触发 ORM语句,如下:
$posts = Post::latest()
->filter(request(['month', 'year']))
->get();
二、static 在类中的延迟静态绑定
Ref: PHP static关键字的用法及注意点
延迟静态绑定:指允许在一个静态继承的上下文中引用被调用类。
延迟绑定的意思为:static::不再为定义当前方法所在的类,而是实际运行时所在的类。注:它可以用于(但不限于)静态方法的调用。
单元测试
一、测试过程
- 一次测试
[1] 调用 phpunit 命令。
[2] 对ExampleTest.php进行单元测试。
[3] 测试的代码:ExampleTest.php
class ExampleTest extends TestCase
{
public function testBasicTest()
{
$response = $this->get('/');
$response->assertStatus(200); $this->get('/')->assertSee('The Bootstrap Blog');
}
}
- $factory 自动封装了testing & seeding
Ref: [Laravel] 08 - Auth & Data Migration
[1] 原封装
/*
|--------------------------------------------------------------------------
| Model Factories
|--------------------------------------------------------------------------
|
| Here you may define all of your model factories. Model factories give
| you a convenient way to create models for testing and seeding your
| database. Just tell the factory how a default model should look.
|
*/ $factory->define(App\User::class, function (Faker\Generator $faker) {
return [
'name' => $faker->name,
'email' => $faker->email,
'password' => bcrypt(str_random(10)),
'remember_token' => str_random(10),
];
});
[2] 根据自己的数据表修改内容
- 使用 $factory 进行 数据填充
[ExampleTest.php]
class ExampleTest extends TestCase
{
use DatabaseTransaction;
public function testBasicTest()
{
// 生成两条数据
$first = factory(Post::class)->create();
$second = factory(Post::class)->create([
'created_at' => \Carbon\Carbon::now()->subMonth()
]); // When I fetch the archives.
$Posts = post::archives();
// Then the response should be in the proper format.
$this->assertCount(2, $posts); # '断言'限定了只能为两条
}
}
运行这个单元测试:
$ phpunit tests/Unit/ExampleTest.php
$this->assertCount(...);
$this->assertCount(0, ['foo']); //判断数组长度是否为传入参数
$this->assertEquals(...);
$this->assertEquals([
[
"year" => $first->created_at->format('Y'),
"month" => $first->created_at->format('F'),
"published" => 1
],
[
"year" => $second->created_at->format('Y'),
"month" => $second->created_at->format('F'),
"published" => 1
],
], $posts);
如果,模型中返回的数据不符合条件,例如忘记了 orderByRaw,那么上述 assertEquals 就会报错。