۱ پویا پارسایی
نحوه استفاده از faker در تست‌های lumen
جامعه پی اچ پی ایجاد شده در ۰۹ اردیبهشت ۱۴۰۱

سلام و عرض ادب.

جهت استفاده از faker در کلاسهای تست لومن میتونیم از این روش استفاده کنیم.

۱- ایجاد یک trait به نام Faker در دایرکتوری تست‌ها و به صورت زیر:

namespace Tests\\Api\\Contracts;
use Faker\\Factory;
use Faker\\Generator;
trait Faker
{
    /**
     * The Faker instance.
     *
     * @var \\Faker\\Generator
     */protected $faker;
    /**
     * Setup up the Faker instance.
     *
     * @return void
     */protected function setUpFaker()
    {
        $this->faker = $this->makeFaker();
    }
    /**
     * Get the default Faker instance for a given locale.
     *
     * @param  string|null  $locale
     * @return \\Faker\\Generator
     */protected function faker($locale = null)
    {
        return is_null($locale) ? $this->faker : $this->makeFaker($locale);
    }
    /**
     * Create a Faker instance for the given locale.
     *
     * @param  string|null  $locale
     * @return \\Faker\\Generator
     */protected function makeFaker($locale = null)
    {
        $locale = $locale ?? (Factory::DEFAULT_LOCALE);
        if (isset($this->app) && $this->app->bound(Generator::class)) {
            return $this->app->make(Generator::class, ['locale' => $locale]);
        }
        return Factory::create($locale);
    }
}

۲- use کردن این trait در کلاس تست:

namespace Tests\\Api\\V1\\Categories;
use App\\Repositories\\Contracts\\CategoryRepositoryInterface;
use Tests\\Api\\Contracts\\Faker;
use Tests\\TestCase;
class CategoryTest extends TestCase
{
    use Faker;
}

۳- در هر متدی که خواستیم از این trait استفاده کنیم باید ابتدا متد setUpFaker این trait رو صدا بزنیم. به این صورت:

namespace Tests\\Api\\V1\\Categories;
use App\\Repositories\\Contracts\\CategoryRepositoryInterface;
use Tests\\Api\\Contracts\\Faker;
use Tests\\TestCase;
class CategoryTest extends TestCase
{
    use Faker;
    private function createCategories($count = 1)
    {
        $this->setUpFaker();
        $categoryRepository = $this->app->make(CategoryRepositoryInterface::class);
        $categories = [];
        foreach (range(0, $count) as $item) {
            $newCategory = [
                'name' => $this->faker->name,
                'slug' => $this->faker->slug
            ];
            $categories[] = $categoryRepository->store($newCategory);
        }
        return $categories;
    }
}

امیدوارم بدردتون بخوره.

سلام دوست عزیز

ممنون بابت اینکه دانشتون رو در اختیار دوستانتون قرار میدین ??

محمد گازری ۰۹ اردیبهشت ۱۴۰۱، ۰۶:۵۸