参考链接:https://laravel-news.com/seeding-data-testing

迁移文件

修改 database/migrations/2014_10_12_000000_create_users_table.php

class CreateUsersTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->string('email')->unique();
$table->string('password');
$table->rememberToken();
$table->timestamps();
}); // following table is storing the relationship between users
// user_id is following follow_user_id
Schema::create('following', function (Blueprint $table) {
$table->integer('user_id')->unsigned()->index();
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade'); $table->integer('follow_user_id')->unsigned()->index();
$table->foreign('follow_user_id')->references('id')->on('users')->onDelete('cascade'); $table->timestamps();
});
} /**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('following');
Schema::dropIfExists('users');
}
}

执行迁移

php artisan migrate
Migration table created successfully.
Migrated: 2014_10_12_000000_create_users_table
Migrated: 2014_10_12_100000_create_password_resets_table

User Model

修改 app/User.php

class User extends Authenticatable
{
use Notifiable; /**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'name', 'email', 'password',
]; /**
* The attributes that should be hidden for arrays.
*
* @var array
*/
protected $hidden = [
'password', 'remember_token',
]; public function follows(User $user)
{
$this->following()->attach($user->id);
} public function unfollows(User $user)
{
$this->following()->detach($user->id);
} public function following()
{
return $this->belongsToMany('App\User', 'following', 'user_id', 'follow_user_id')->withTimestamps();
} public function isFollowing(User $user)
{
return !is_null($this->following()->where('follow_user_id', $user->id)->first());
}
}

这里使用了多对多用户关系关联方法[1]

种子文件

创建一个种子文件 database/seeds/UsersTableSeeder.php

php artisan make:seeder UsersTableSeeder

在种子文件中使用工厂方法[2]

use App\User;
use Illuminate\Database\Seeder; class UsersTableSeeder extends Seeder
{
/**
* Run the database seeds.
*
* @return void
*/
public function run()
{
$users = factory(User::class, 10)->create();
}
}

执行种子文件

  1. 方式一
php artisan db:seed --class=UsersTableSeeder
  1. 方式二

database/seeds/DatabaseSeeder.php 中注册种子文件

class DatabaseSeeder extends Seeder
{
/**
* Run the database seeds.
*
* @return void
*/
public function run()
{
$this->call(UsersTableSeeder::class);
}
}

执行这个 DatabaseSeeder 这个大种子。

php artisan db:seed

测试用例

创建一个测试用例。

php artisan make:test Feature\UserTest

修改 tests/Feature/UserTest.php 的内容。

use App\User;

class UserTest extends TestCase
{
public function test_have_10_users()
{
$this->assertEquals(10, User::count());
}
}

执行测试

vendor\bin\phpunit

完整的测试文件

<?php

use App\User;
use Illuminate\Foundation\Testing\WithoutMiddleware;
use Illuminate\Foundation\Testing\DatabaseMigrations;
use Illuminate\Foundation\Testing\DatabaseTransactions; class UserTest extends TestCase
{ use DatabaseTransactions; public function test_follows()
{
$userA = User::find(2);
$userB = User::find(3); $userA->follows($userB); $this->assertEquals(1, $userA->following()->count());
} public function test_unfollows()
{
$userA = User::find(3);
$userB = User::find(2); $userA->unfollows($userB); $this->assertEquals(0, $userA->following()->count());
} public function test_A_follows_B_and_C()
{
$userA = User::find(1); $ids = collect([2, 3, 4, 5, 6, 7, 8, 9, 10]);
$random_ids = $ids->random(2); $userB = User::find($random_ids->pop());
$userC = User::find($random_ids->pop()); $userA->follows($userB);
$userA->follows($userC); $this->assertEquals(2, $userA->following()->count());
}
}

每执行一次测试,都会在数据库表中插入数据。因此这一次运行结果和前一次可能不一样

我们不得不像下面这样,每执行一次测试,就得重新 refresh & seeding吗?

php artisan migrate:refresh --seed
vendor\bin\phpunit

不用!加上 DatabaseTransactions 就好了。

class UserTest extends TestCase
{
use DatabaseTransactions; ...
}

这个 Trait 将所有测试项放在一个事务中。无论执行结果如何(全部成功或者没全部成功)都不会对之前的数据库数据造成任何影响,也就是说这个事务在最后总是回滚

tags: Laravel 项目

  1. belongsToMany 方法用来定义多对多关系。它的第一个参数是关联表(这里是自关联,用户关注用户);第二个参数是中间表名(这里定义为 following);第三个参数是 $this 指代的 Model 的主键在中间表里的字段名;第四个参数是对应表(这里指被关注的人,对应的还是 users 表)的主键在中间表里的字段名。 ↩︎

  2. 工厂方法在 database/factories 下定义,可以定义在 ModelFactory.php 中,也可以定义在基于 Model 的工厂方法里(比如 UserFactory.php)。它们都会被 Laravel 处理。 ↩︎

Laravel 测试教程的更多相关文章

  1. Laravel初级教程浅显易懂适合入门

    整理了一些Laravel初级教程,浅显易懂,特适合入门,留给刚学习laravel想快速上手有需要的朋友 最适合入门的laravel初级教程(一)序言 最适合入门的laravel初级教程(二)安装使用 ...

  2. 最适合入门的Laravel中级教程(一)

    Laravel 是一个全栈框架: 我们使用 Laravel 开发业务常见有 3 个方向: 前端页面和后端逻辑混合的应用 主要是面向对 SEO 有需求的项目: 比如说新闻资讯博客文章等: 一般在控制器中 ...

  3. MyCat安装与测试教程 超详细!

    MyCat安装与测试教程 超详细! MyCat基础知识 一.什么是MYCAT? 1. 一个彻底开源的,面向企业应用开发的大数据库集群 2. 支持事务.ACID.可以替代MySQL的加强版数据库 3. ...

  4. Kail Linux渗透测试教程之免杀Payload生成工具Veil

    Kail Linux渗透测试教程之免杀Payload生成工具Veil 免杀Payload生成工具——Veil Kail Linux渗透测试教程之免杀Payload生成工具Veil,Veil是一款利用M ...

  5. Kail Linux渗透测试教程之网络扫描和嗅探工具Nmap

    Kail Linux渗透测试教程之网络扫描和嗅探工具Nmap 网络扫描和嗅探工具——Nmap Nmap也就网络映射器(Network Mapper),是一个免费开放的网络扫描和嗅探工具.该工具可以扫描 ...

  6. Mac环境下RabbitMq安装与测试教程

    RabbitMq安装与测试教程 Installing on Mac I. 安装 123456789 brew install rabbitmq ## 进入安装目录cd /usr/local/Cella ...

  7. monkey测试===monkeyrunner测试教程(1)

    1.安装测试环境 jdk 安装与配置 android sdk安装与配置 Python编辑器安装与配置 以上安装请自行百度教程 Monkeyrunner使用方法 http://www.android-d ...

  8. 深度相机Astra Pro测试教程

    最近在微信群内,很多群友在群友的推荐下,购买了Astra pro的深度相机,价格地道,物超所值!群友反馈积极,所以这里出一波简单的教程.   以下内容知识抛砖引玉,主要讲解windows下和Ubunt ...

  9. Unity导出iOS真机测试教程

    原地址:http://unity3d.9tech.cn/news/2014/0410/40177.html 学 习了两天的Android开发,我感觉Android开发跟IOS开发和.NET平台下的开发 ...

随机推荐

  1. CoreDNS kubernetes 安装使用

     kubernetes 以前是skydns 后面变为 dnsmasq,coredns 也是一个不错的工具 1. 准备环境 安装 kubernetes 配置 kubelet 的cluster-dns 2 ...

  2. 从如何优化SQL入手,提高数据仓库的ETL效率

    1        引言数据仓库建设中的ETL(Extract, Transform, Load)是数据抽取.转换和装载到模型的过程,整个过程基本是通过控制用SQL语句编写的存储过程和函数的方式来实现对 ...

  3. Tomcat起了一个测试桩,调用该测试桩无响应

    有时在测试新业务流程时因为涉及多个不同接口的调用,而这些被调用的服务端因为网络权限或开发进度问题暂时对我们不可达,那么我们可以通过模拟接口返回来完成我们新业务的测试.这次碰到的问题是我明明起了该测试桩 ...

  4. 关于yii2的中文乱码问题

    在数据库配置中这么配就可以了 <?php return [ 'class' => 'yii\db\Connection', 'dsn' => 'mysql:host=127.0.0. ...

  5. 南阳OJ 1170 最大的数

    最大的数 时间限制:1000 ms  |  内存限制:65535 KB 难度:3   描述 小明和小红在打赌说自己数学学的好,于是小花就给他们出题了,考考他们谁NB,题目是这样的给你N个数 在这n个数 ...

  6. 事务之二:spring事务(事务管理方式,事务5隔离级别,7个事务传播行为,spring事务回滚条件)

    事物管理对于企业应用来说是至关重要的,好使出现异常情况,它也可以保证数据的一致性. spring支持编程式事务管理和声明式事务管理两种方式. 编程式事务管理使用TransactionTemplate或 ...

  7. Annotation之一:Java Annotation基本功能介绍

    一.元数据的作用 如果要对于元数据的作用进行分类,目前还没有明确的定义,不过我们可以根据它所起的作用,大致可分为三类: 编写文档:通过代码里标识的元数据生成文档.这是最常见的,也是java 最早提供的 ...

  8. python学习(四) 字典:当索引不好用时

    第四章 字典:当索引不好用时 4.1 字典的使用 字典的适用场景: 表示一个游戏棋盘的状态,每个键都是由坐标值组成的元组: 存储文件修改时间,用文件名作为键: 数字电话/地址簿 4.2 创建和使用字典 ...

  9. U-boot分析与移植(2)----U-boot stage1分析

    我们要生成u-boot.bin文件,它首先依赖于很多.o文件和.lds链接脚本文件 我们只要找到对应的.lds链接脚本文件就可以分析u-boot的启动流程. 1.打开u-boot-1.1.6\u-bo ...

  10. 解决:An internal error occurred during: "Launching New_configuration". Path for project must have only one segment.

    问题: 点击运行时eclipse报错如下: An internal error occurred during: "Launching New_configuration". Pa ...