Factory helper not working within PHPUnit setup method

Viewed 1419

Writing some unit tests, and I want to have an object created before the tests in the class are done. So I set up the setUpBeforeClass() method:

<?php
namespace Tests\Unit;
use Tests\TestCase;
use App\Location;
class UserTests extends TestCase {
    const FAKEID = 9999999;
    public static function setUpBeforeClass() : void {
        parent::setUpBeforeClass();
        factory(Location::class)->make(["id" => self::FAKEID])->save();
    }
}

But when I try running this, I get this error:

InvalidArgumentException: Unable to locate factory with name [default] [App\Location].

But the factory class is set up properly. In fact, if I move this same line down to one of my test functions it works perfectly.

public function testCreateUser() {
    factory(Location::class)->make(["id" => self::FAKEID])->save();
    // do other stuff...
}

The only thing that sticks out to me as different about setUpBeforeClass() is that it's a static method, but I don't know why that would prevent the factory class from working.

1 Answers

Laravel does a lot of setting up in the setUp() method in the TestCase class. The setUpBeforeClass() method is called before that, that's why your factory is not loaded yet.

The Laravel's TestCase class setup method (see class):

/**
 * Setup the test environment.
 *
 * @return void
 */
protected function setUp()
{
    if (! $this->app) {
        $this->refreshApplication();
    }

    $this->setUpTraits();

    foreach ($this->afterApplicationCreatedCallbacks as $callback) {
        call_user_func($callback);
    }

    Facade::clearResolvedInstances();
    Model::setEventDispatcher($this->app['events']);

    $this->setUpHasRun = true;
}

Change your code to use setUp instead:

protected static function setUp() : void 
{
    parent::setUp();

    factory( Location::class )->make( ["id" => self::FAKEID] )->save();
}
Related