Laravel model mock

488 views Asked by At

I am trying to mock a model and return false on insert so i can test failure case.

here is my test mocking

$mockModel = Mockery::mock(\App\Models\MyModel::class)->shouldReceive(['insertGetId'])->once()->andReturn(false);

and here is my insert method in controller

$result = MyModel::insertGetId(['something' => 'somevalue',]);
dd($result);

and i am expecting $result to be false but instead i get the id (int).

if i remove dd(); i get this error on the terminal.

Mockery\Exception\InvalidCountException: Method insertGetId() from Mockery_0_App_Models_MyModel should be called
 exactly 1 times but called 0 times.
1

There are 1 answers

5
Mayank Pandeyz On

You are using insertGetId() which returns the inserted id. Use insert() instead.

If the table has an auto-incrementing id, use the insertGetId method to insert a record and then retrieve the ID like:

$id = DB::table('users')->insertGetId(
    ['email' => '[email protected]', 'votes' => 0]
);

but in case of insert it return true or false based on success or failure of query.