前言


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

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. CocosCreator动作系统

    废话没有,直接上代码,有注释可以看的, cc.Class({ extends: cc.Component, properties: { player:{ default:null, type:cc.N ...

  2. Java 数组元素倒序的三种方式

    将数组元素反转有多种实现方式,这里介绍常见的三种. 直接数组元素对换 @Test public void testReverseSelf() throws Exception { System.out ...

  3. Java全栈程序员之02:Ubuntu下Java环境安装、配置、测试

    在上文讲完之后,我们手里的ubuntu只能算是一个上网机,什么也干不了,本篇我们将折腾它为开发机. 这里,我们这里假定你对linux体系是初级选手,所以本篇会讲的啰嗦一点,高手就出门左转吧. 1.安装 ...

  4. Linux下阅读MHT文件

    Linux下阅读MHT文件 2016年02月04日 15:11:32 dj0379 阅读数:1769   mht是一种WEB电子邮件档案,用IE选择保存网页类型时可以看到有这一项,其最大优点是所保存的 ...

  5. .NetCore中EFCore的使用整理(二)-关联表查询

    EF常用处理关联加载的方式有3中:延迟加载(Lazy Loading).贪婪加载 (Eager Loading)以及显示加载. 一.EF Core  1.1 1.当前的版本,还不支持延迟加载(Lazy ...

  6. Go语言之高级篇beego框架之Controller

    一.Controller 控制器 Controller等同于Django里的view,处理逻辑都是在Controller里面完成的,下面就写一个最简单的Controller.写controller的时 ...

  7. 版本控制-GitHub

    前面几篇文章,我们介绍了Git的基本用法及Git服务器的搭建,本篇文章来学习一下如何使用GitHub.GitHub是开源的代码库以及版本控制库,是目前使用网络上使用最为广泛的服务,GitHub可以托管 ...

  8. Linux 下hosts文件详解

    1.主机名: 无论在局域网还是INTERNET上,每台主机都有一个IP地址,是为了区分此台主机和彼台主机,也就是说IP地址就是主机的门牌号. 公网:IP地址不方便记忆,所以又有了域名.域名只是在公网( ...

  9. IIS 之 应用程序池

    IIS(Internet Information Services),由于我使用的是Windows10系统,所以本文以其内置 10.0.14393.0 版本说明. 应用程序池 → 右键(待设置应用程序 ...

  10. C++ 匿名namespace的作用以及与static的区别

    匿名namespace的作用以及它与static的区别 一.匿名namespace的作用 在C语言中,如果我们在多个tu(translation unit)中使用了同一个名字做 为函数名或者全局变量名 ...