Alexandra Axt
Alexandra Axt

Reputation: 1346

Use custom Faker method in Laravel PHPunit: Unknown formatter

I created a FakerServiceProvider. I tested it in a test route and it works fine:

Route::get('test', function() {
    $faker = app('Faker');
    echo $faker->customMethod;
  });

I want to use this custom faker method in my PHPunit tests in ModelFactory.php, and there I get error:

InvalidArgumentException: Unknown formatter customMethod

In my unit tests I use this faker method in database/factories/ModelFactory.php to generate models:

$factory->define(CustomClass::class, function (Faker\Generator $faker) {
    dump($faker);
    return [
        'text' => $faker->customMethod
    ];
});

When I dump $faker in my test route, then my custom FakerProvider is there. But if I dump it in ModelFactory method, then not. Why?

Edit: Register method of my FakerServicePRovider

public function register()
    {
        $this->app->singleton('Faker', function($app) {
            $faker = \Faker\Factory::create();
            $newClass = new class($faker) extends \Faker\Provider\Base {

            public function customMethod()
                {
                    return "blabla";
                }
            };

            $faker->addProvider($newClass);
            return $faker;
        });
    }

Upvotes: 0

Views: 899

Answers (1)

Salim Djerbouh
Salim Djerbouh

Reputation: 11034

Because the ModelFactory uses the Faker base not extended, you should use your own instead

'text' => app('Faker')->customMethod

Upvotes: 2

Related Questions