简体   繁体   中英

Mocking laravel DB facades when method using mockery/mockery

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.

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.

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:

  1. Get all users (even users with email_verified_at ).
  2. Get all users that have email_verified_at as null .

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();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM