Summer Sale! All accounts are 50% off this week.

timgavin's avatar

Testbench: Error: Class "App\Models\User" not found

After a few years hiatus from Laravel, I'm finally getting around to learning how to create packages and perform unit tests.

My first package is a very simple one: a user can block another user. The package works great, but when trying to write my first test I get the error: Error: Class "App\Models\User" not found, even though it's clearly imported.

Even if I inline it instead of using a factory it still throws that error.

// this also throws an error
\App\Models\User::create(['John', '[email protected]','12345678']);

Here's my test

<?php

namespace TimGavin\LaravelBlock\Tests;

use App\Models\User;
use Illuminate\Foundation\Testing\DatabaseMigrations;
use Orchestra\Testbench\TestCase;

class BlockTest extends TestCase
{
    use DatabaseMigrations;

    /** @test */
    public function a_user_can_block_another_user()
    {
        $userA = User::factory()->create();
        $userB = User::factory()->create();

        $userA->block($userB);
    }
}

Here's the error

1) TimGavin\LaravelBlock\Tests\BlockTest::a_user_can_block_another_user
Error: Class "App\Models\User" not found

If I remove the user inserts and block check, and just replace with $this->assertTrue(true); the test passes. So weird.

What am I doing wrong?

0 likes
5 replies
Sinnbeck's avatar
Sinnbeck
Best Answer
Level 102

As this is a package I don't assume you actually have a user model?

timgavin's avatar

@Sinnbeck Thought I was using the one that ships with Laravel? I need to supply my own in the package?

Sinnbeck's avatar

@timgavin laravel does not ship with that model as such. You get it in the project when you install laravel. But in theory you could rename, move or delete it

So I assume your package uses a trait that they need to add to the user model? In that case you can add a fake user model \YourPackage\Tests\Models\User

timgavin's avatar

@Sinnbeck Ok, that makes a lot of sense. I'll study those and straighten it out. Thanks!

Please or to participate in this conversation.