iralance / myblog

notes
0 stars 0 forks source link

laravel phpunit #36

Open iralance opened 6 years ago

iralance commented 6 years ago

Eloquent Model

Create Model and Migrations

php artisan make:model Article -m

Edit Migrations

public function up()
    {
        Schema::create('articles', function (Blueprint $table) {
            $table->increments('id');
            $table->string('title');
            $table->unsignedInteger('reads')->default(0);
            $table->timestamps();
        });
    }

Using Model Factories

php artisan make:factory ArticleFactory

$factory->define(\App\Article::class, function (Faker $faker) {
    return [
        'title' => $faker->title(),
        'reads' => $faker->numberBetween(10,2000),
    ];
});

Create Test Database

edit config\database.php add the following content

'mysql_test' => [
'driver' => 'mysql',
'host' => env('DB_HOST', '127.0.0.1'),
'port' => env('DB_PORT', '3306'),
'database' => env('DB_DATABASE_TEST', 'forge'),
'username' => env('DB_USERNAME_TEST', 'forge'),
'password' => env('DB_PASSWORD_TEST', ''),
'unix_socket' => env('DB_SOCKET', ''),
'charset' => 'utf8mb4',
'collation' => 'utf8mb4_unicode_ci',
'prefix' => '',
'strict' => true,
'engine' => null,
],

add .env

DB_DATABASE_TEST=laravel-phpunit-test
DB_USERNAME_TEST=
DB_PASSWORD_TEST=

running test migrate

php artisan migrate --database=mysql_test

edit phpunit.xml add the following content

<env name="DB_CONNECTION" value="mysql_test"/>

Create ArticleTest

补充说明:phpunit的测试方法需以test开头命名方法名,或者下面方式,在方法名前加注释。mark:option+shift+u 转换成小写 command+option+m 代码块变成方法


php artisan make:test ArticleTest

<?php

namespace Tests\Feature;

use App\Article; use Illuminate\Foundation\Testing\DatabaseTransactions; use Tests\TestCase; use Illuminate\Foundation\Testing\WithFaker; use Illuminate\Foundation\Testing\RefreshDatabase;

class ArticleTest extends TestCase { use DatabaseTransactions;//truncate table; /**

参考链接

wueason commented 6 years ago

nice

shenjinhui88 commented 6 years ago

nice