前言


实现一个博客的侧边栏的链接,然后顺便对其进行单元测试的过程。

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 就会报错。

[Laravel] 15 - REST API: sidebar with unit test的更多相关文章

  1. 利用Laravel 搭建oauth2 API接口 附 Unauthenticated 解决办法

    利用Laravel 搭建oauth2 API接口 要求 laravel 5.4以上 安装 $ composer require laravel/passport 在配置文件 config/app.ph ...

  2. [Laravel] 14 - REST API: Laravel from scratch

    前言 一.基础 Ref: Build a REST API with Laravel API resources Goto: [Node.js] 08 - Web Server and REST AP ...

  3. Laravel POST请求API接口 使用validate表单验证返回欢迎页

    突然遇到的问题  就是使用Laravel进行开发API接口的时候  发现在表单验证不通过的时候返回了登录页 猜测问题应该是因为表单验证失败后进行了重定向导致的 因为返回状态码200 网上找了好久没找到 ...

  4. laravel jwt 做API 退出登录(注销) 该怎么弄? 如何让token失效

    laravel jwt 做API 退出登录(注销) 该怎么弄? 如何让token失效 php框架 laravel 2.1k 次浏览 问题对人有帮助,内容完整,我也想知道答案0问题没有实际价值,缺少关键 ...

  5. laravel使用Dingo\Api通过response()->json()返回空对象

    laravel使用Dingo\Api写接口跟android对接时,android一直反应解析错误,无法解析数据. { "status_code":200, "messag ...

  6. laravel 配置路由 api和web定义的路由的区别详解

    1.路由经过中间件方面不同 打开kerenl.php就可以看到区别 protected $middlewareGroups = [ 'web' => [ \App\Http\Middleware ...

  7. 【转】简单的 Laravel 5 REST API

    Introduction Almost all successful internet based companies have APIs. API is an acronym for Applica ...

  8. Laravel 的 JSON API 接口自动化测试

    Laravel 自带了两种测试类型 Feature Test: 功能测试.针对类似接口这种流程性的测试. Unit Test: 单元测试.针对单个函数这种输入输出结果的测试. 新建一个 Feature ...

  9. [Laravel] 10 - WEB API : wrapper

    前言 一.常用的解决方案 React 前端 + PHP (Laravel) 后端 Such as "some exposure to WEB API’s and/or RESTful“. 使 ...

随机推荐

  1. 系统wmiprvse.exe占用CPU非常高,求解决

    1.wmiprvse.exe是微软Windows操作系统的一部分.用于通过WinMgmt.exe程序处理WMI操作.文件位置有二处: C:\WINDOWS\system32\wbem\wmiprvse ...

  2. Spring boot设置文件上传大小限制

    原文:https://blog.csdn.net/lizhangyong1989/article/details/78586421 Spring boot1.0版本的application.prope ...

  3. 如何在本地搭建一个Android应用crashing跟踪系统-ACRA

    https://github.com/bboyfeiyu/android-tech-frontier/tree/master/others/%E5%A6%82%E4%BD%95%E5%9C%A8%E6 ...

  4. 深入理解 Java try-with-resource 语法糖

    背景 众所周知,所有被打开的系统资源,比如流.文件或者Socket连接等,都需要被开发者手动关闭,否则随着程序的不断运行,资源泄露将会累积成重大的生产事故. 在Java的江湖中,存在着一种名为fina ...

  5. C#中Split用法【转】

    https://www.cnblogs.com/webenh/p/6570801.html 1.用字符串分隔: using System.Text.RegularExpressions;string  ...

  6. IOPS计算

    Device Type IOPS 7,200 rpm SATA drives HDD ~75-100 IOPS[2] 10,000 rpm SATA drives HDD ~125-150 IOPS[ ...

  7. 动态库DLL中类的使用

    一.DLL中类的导出 在类名称前添加 _declspec(dllexport)定义,比如: class _declspec(dllexport) CMath{ .... }; 通常使用预编译开关切换类 ...

  8. 【PMP】合同类型

    合同类型与适用场景 图形解读: 总价类 (1)固定总价类合同:货物的采购价格在一开始就已确定,并且不允许改变(除非工作范围发生变更) (2)总价加激励费合同:同会设置价格上限,高于此价格的上限的全部成 ...

  9. win8下C盘不能读写的解决方案[zz]

    做系统安全的时候发现了这个/setintegritylevel参数,没有找到更多资料,找到此文,看来这个参数有点神奇哟!我一个同事遇到了这个问题,主要症状:1.C 盘文件不能修改2.C 盘不能新建文件 ...

  10. 一个正整数表示为n个连续正整数之和(第1届第2题)

    题目要求 问题描述:一个正整数有可能可以被表示为 n(n>=2) 个连续正整数之和,如: 15=1+2+3+4+5 15=4+5+6 15=7+8 编写程序,根据输入的任何一个正整数,找出符合这 ...