Yii2 使用 faker 生成假数据

测试过程中有时候需要生成大量的假数据,faker 是一个生成假数据的类库.Yii2.0已经集成该类库yii2-faker,不用再下载了。

以Yii2.0 advanced版为例:

1. console\config\main-local.php中添加一条配置信息

'controllerMap' => [
    'fixture' => [
        'class' => 'yii\faker\FixtureController',
    ],
],

注意顶部,定义tests测试目录的位置的代码。在console\config\bootstrap.php中添加

Yii::setAlias('@tests', dirname(__DIR__) . '/tests');

2. 创建生成假信息的模版文件

在tests目录下面依次新建unit/templates/fixtures目录,然后在fixtures目录下新建blogs.php文件。内容如下:

<?php
// users.php file under template path (by default @tests/unit/templates/fixtures)
/**
 * @var $faker \Faker\Generator
 * @var $index integer
 */
return [
    'title' => $faker->title,
    'content' => $faker->realText,
    'views' => $faker->firstName,
    'is_delete' => $faker->boolean,
    'created_at' => $faker->date($format = 'Y-m-d', $max = 'now'),
    'updated_at' => $faker->date($format = 'Y-m-d', $max = 'now'),
    'file' => $faker->imageUrl($width = 640, $height = 480),
    'file2' => $faker->imageUrl($width = 640, $height = 480),
];

3. 打开命令行,执行生成假记录命令

php yii fixture/generate users --count=10
git bash

生成的假数据位于tests\unit\fixtures\data\blogs.php,打开如下,有了假数据内容,剩下的就好办了

<?php

return [
    [
        'title' => 'Miss',
        'content' => 'King, with an anxious look at it!\' This speech caused a remarkable sensation among the people that walk with their fur clinging close to her, still it had VERY long claws and a crash of broken.',
        'views' => '丽丽',
        'is_delete' => true,
        'created_at' => '1977-04-04',
        'updated_at' => '2013-06-04',
        'file' => 'https://lorempixel.com/640/480/?42094',
        'file2' => 'https://lorempixel.com/640/480/?90710',
    ],
    [
        'title' => 'Mrs.',
        'content' => 'As soon as look at me like that!\' But she waited patiently. \'Once,\' said the Queen. \'Their heads are gone, if it please your Majesty,\' said the one who had spoken first. \'That\'s none of YOUR.',
        'views' => '帅',
        'is_delete' => true,
        'created_at' => '1996-08-25',
        'updated_at' => '2012-04-09',
        'file' => 'https://lorempixel.com/640/480/?44425',
        'file2' => 'https://lorempixel.com/640/480/?16747',
    ],
    ...
]
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 135,026评论 19 139
  • Composer Repositories Composer源 Firegento - Magento模块Comp...
    零一间阅读 3,970评论 1 66
  • 包管理Package Management Libraries for package and dependenc...
    CaptainKK阅读 6,019评论 5 50
  • 360加固成功脱壳 链接1:http://bbs.pediy.com/thread-210275.htm 链接2:...
    playboy阅读 1,393评论 2 6
  • 我的头很痛 但又怎比得上心痛 我的 你的 我对不起你 可我想保护你一辈子
    昵喃侨北久醉不归阅读 182评论 0 0