A
A
asdasdqwe2022-01-19 19:40:38
Laravel
asdasdqwe, 2022-01-19 19:40:38

How to create a mock for models?

Controller

public function index(Request $request)
    {
       $users =  User::all();
        return view('index', compact('users '));
    }

Test
public function test_index()
    {
       // Куда передать этот мок?
        $mock = $this->mock(User::class, function (MockInterface $mock) {
            $mock->shouldReceive('all')->once()->andReturn([]);
        });

        $response = $this->get('/')
        ->assertViewHasAll(['users'])
    }

Result: Method all() from Mockery_0_App_Models_User should be called
exactly 1 times but called 0 times.

Facades work automatically (Mail::fake(), Event::fake() etc)

How to create a mock model to pass own data instead of all()?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
Vyacheslav Plisko, 2022-01-20
@AmdY

Since you are using facades, mock them User::shouldReceive ....
https://laravel.com/docs/8.x/mocking

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question