-1

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.

KevDev
  • 541
  • 2
  • 6
  • 20

2 Answers2

0

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.

mrhn
  • 17,961
  • 4
  • 27
  • 46
  • thank you of this idea. but It didn't on my end. I got this error. may I did it wrong https://pastebin.com/zurAS9KH – KevDev Nov 27 '21 at 00:09
  • 1
    This seems like to be an error related to wrong phpunit version compared to the php version running it – mrhn Nov 27 '21 at 00:24
  • yes your right. my phpstorm is running php8 and i got phpunit 9.5 but i run it using php7.4.. i still got an error. https://pastebin.com/0uNngrJH – KevDev Nov 27 '21 at 01:14
  • It doesnt find any testcase what is your class names like and whicj testcase does they extend? – mrhn Nov 27 '21 at 11:57
-1

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();
matiaslauriti
  • 7,065
  • 4
  • 31
  • 43