mockery icon indicating copy to clipboard operation
mockery copied to clipboard

mocking laravel db facade on `when` method

Open besingamkb opened this issue 4 years ago • 1 comments

Hi,

I am using laravel with mockery to unit test my queries.. how can I mock the when method of laravel db query using mockery? so here is what I want to test..

<?php
// ... TestRepo.php
class TestRepo
{
    public function testQb()
    {
        DB::table('users')
            ->when(true, function($query) {
                $query->where('email_verified_at', null);
            })
            ->get();
    }
}

and here is what my test look like..

/**
 * A basic test example.
 *
 * @return void
 */
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);
}

the only missing on this test is the part where the when method is being called. is this possible to mock also on mockery? and how can I do that? thanks in advance

besingamkb avatar Nov 25 '21 21:11 besingamkb

Not overly familiar with Laravel's facade/mockery support, so not entirely sure if I'm honest, but you could try adding:

    DB::shouldReceive('when')->andReturnSelf();

davedevelopment avatar Jan 11 '22 09:01 davedevelopment