I am using mockery/mockery to mock laravel db facade on my unit test. But I don't know how to create a stub for the when method. So here is my class that I want to test.
<?php
namespace App;
use Illuminate\Support\Facades\DB;
class TestRepo
{
public function testQb()
{
DB::table('users')
->when(true, function($query) {
$query->where('email_verified_at', null);
})
->get();
}
}
and I want to make sure that the querybuilder runs the when
method including the clousure.
so far I have this test without the stub for when
method
public function test_example()
{
DB::shouldReceive('table')->once()->with('users')->andReturnSelf();
DB::shouldReceive('get')->once()->andReturn(collect(new User()));
(new TestRepo())->testQb();
$this->assertTrue(true);
}
this will test will fail because I dont have a stub for laravel db facade when
method.
can somebody tells me how can I achieve this? thank you in advance.
CodePudding user response:
Mockery can mock methods chains, as described here.
DB::shouldReceive('table->when->get')->andReturn(collect(new User()));
But as this has less assertions by avoiding with()
, i would suggest asserting the return data.
CodePudding user response:
You don't have to do that, you are literally testing the Facade not your logic/flow. You must never test core
code as that is already tested.
The way of testing that code is to do a Feature or Unit Test for each case:
- Get all
users
(evenusers
withemail_verified_at
). - Get all
users
that haveemail_verified_at
asnull
.
In both cases, you have to have users
with both conditions, and only the first condition will return all users
, but the second one should not return a user were email_verified_at
is not null
.
Your query can be upgraded:
use Illuminate\Database\Eloquent\Builder;
User::when(true, function (Builder $query) {
return $query->whereNull('email_verified_at');
})
->get();