Laravel 5.2测试如何遵循DRY原则?

时间:2016-10-21 10:30:06

标签: laravel unit-testing

每次我需要将方法测试为经过身份验证的用户时,我总是插入角色表,因为它与用户表有关系,然后创建新用户。

喜欢以下代码。

<?php

use Illuminate\Foundation\Testing\WithoutMiddleware;
use Illuminate\Foundation\Testing\DatabaseMigrations;
use Illuminate\Foundation\Testing\DatabaseTransactions;
use App\Models\User;
use App\Models\Role;

class CouponsTest extends TestCase
{
    /**
     * A basic test example.
     *
     * @return void
     */

    use DatabaseMigrations;
    //use WithoutMiddleware;

    public function test_index_coupon(){

        //factory(App\Models\Coupon::class, 5)->create()->toArray();  

       DB::table('roles')->insert([
          ['id' => 1, 'name' => 'customer'],
          ['id' => 2, 'name' => 'partner'],
          ['id' => 3, 'name' => 'admin'],
        ]);


       $user = User::create([
           'id' => 3,
           'password' => bcrypt('123456789'),
           'email' => 'admin@domain.co.id',
           'role_id' => '3',
           'status' => 'confirmed',
           'balance' => 0,
        ]);

        $this->actingAs($user)->visit('admin/coupons')->seePageIs('admin/coupons');


    }


    public function test_create_coupon()
    {

        DB::table('roles')->insert([
          ['id' => 1, 'name' => 'customer'],
          ['id' => 2, 'name' => 'partner'],
          ['id' => 3, 'name' => 'admin'],
        ]);

        $user = User::create([
           'id' => 3,
           'full_name' => 'Admin Full Name',
           'password' => bcrypt('123456789'),
           'email' => 'admin@domain.co.id',
           'role_id' => '3',
           'status' => 'confirmed',
           'balance' => 0,
        ]);

        $this->actingAs($user)->visit('admin/coupons/create')->seePageIs('admin/coupons/create');

    }
}

我知道这是不好的做法。

我的代码应如何遵循DRY原则?

1 个答案:

答案 0 :(得分:0)

通常使用ModelFactory.php并为您的模型定义工厂。

您也可以将参数传递给这些模型。

$factory->define(App\User::class, function (Faker\Generator $faker) {
    static $password;
    return [
        'name' => $faker->name,
        'email' => $faker->unique()->safeEmail,
        'password' => $password ?: $password = bcrypt('secret'),
        'remember_token' => str_random(10),
        'role_id' => factory(App\Role::class)->create()->id,
    ];
});


$factory->define(App\Role::class, function(Faker\Generator $faker){
     return [
         'name' => $faker->name,
     ];
}

然后,您可以在测试中执行以下操作:

$role = factory(App\Role::class)->create(['name' => 'admin']);

$adminUser = factory(App\User::class)->create(['role_id' => $role->id]);

如果需要在许多测试中使用,可以在测试setup()方法中执行一次,并将管理员用户定义为测试类的受保护变量。

请记住,您可能还应该在测试类中使用use DatabaseTransactions; trait,以便在测试结束时删除上述命令创建的任何条目。