测试过程中有时候需要生成大量的假数据,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
生成的假数据位于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',
],
...
]