[Laravel] 15 - REST API: sidebar with unit test

前言


實現一個博客的側邊欄的連接,而後順便對其進行單元測試的過程。php

 

 

 

Archives


1、視圖中展現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 tinkerhtml

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中的參數觸發。 sql

 

  • URL中的時間參數解析【觸發】
if ($month = request('month')) {
  $posts->whereMonth('created_at', Carbon::parse($month)->month);
}

Ref: Laravel Carbon函數數組

也能夠選擇year和month一併解析,而後直接觸發 ORM語句,以下:dom

$posts = Post::latest()
    ->filter(request(['month', 'year']))
    ->get();

 

 

2、static 在類中的延遲靜態綁定

Ref: PHP static關鍵字的用法及注意點函數

延遲靜態綁定:指容許在一個靜態繼承的上下文中引用被調用類。post

延遲綁定的意思爲:static::再也不爲定義當前方法所在的類,而是實際運行時所在的類。注:它能夠用於(但不限於)靜態方法的調用。單元測試

 

 

 

單元測試


1、測試過程

  • 一次測試

[1] 調用 phpunit 命令測試

 

[2] 對ExampleTest.php進行單元測試。fetch

 

[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 就會報錯。

相關文章
相關標籤/搜索