See this thread - are you importing the wrong testcase?
Dec 31, 2019
6
Level 4
Factories do not run in unit test files (but in feature tests, after update 5.4>6)
My factories do not get found in unit test files, but only in feature tests.
Here is the exact same test with the respective class infos. I recently upgraded the app form Laravel 5.4 to 6.0. Maybe I need to adjust some test base classes or the like.
Factory
<?php
/** @var \Illuminate\Database\Eloquent\Factory $factory */
use Faker\Generator as Faker;
$factory->define(App\Note::class, function (Faker $faker) {
return [
'contact_id' => 1,
'type' => 1,
'body' => 'Long sentence',
];
});
Feature test file (passing)
<?php
namespace Tests\Feature\Http\Controllers;
use App\Note;
use Tests\TestCase;
use Illuminate\Foundation\Testing\RefreshDatabase;
class NoteControllerTest extends TestCase
{
use RefreshDatabase;
/** @test */
public function it_does_get_icon_name_for_note_type()
{
$note = factory(Note::class)->create();
$this->assertEquals('Interaction', $note->type_description);
}
}
Unit test file (failing)
<?php
namespace Tests\Unit;
use App\Note;
use Illuminate\Foundation\Testing\RefreshDatabase;
use PHPUnit\Framework\TestCase;
class NoteUnitTest extends TestCase
{
use RefreshDatabase;
/** @test */
public function it_does_get_icon_name_for_note_type()
{
$note = factory(Note::class)->create();
$this->assertEquals('Interaction', $note->type_description);
}
}
Error message: Unable to locate factory with name [default] [App\Note].
Of course I could keep all the unit tests in my feature test sets, but that would be the worst solution.
Level 4
To sum up the answers from @gazd1977 and @nakov and give a reference for future posts:
- Laravel 6.9 changes the default testcase for unit tests from
use Tests\TestCase;touse PHPUnit\Framework\TestCase; - See the commit message and some discussion here: https://github.com/laravel/framework/commit/e30a0c979d98f2f1f7b6c565e4002734237a280b
- To use factories, create feature tests or change the base testcase
Please or to participate in this conversation.