Search code examples
phpunit-testinglaravelmockingmockery

how do I mock the DB facade in laravel?


I'm writing my unit tests and by default they should not hit the database. by general rule I always use eloquent to get the results, but some more complex queries I have to use the raw DB

I have this function:

public function GetPassword($email)
{
    $result = DB::table('vin_user_active')
        ->select(
            "vin_user_active.id",
            "vin_user_active.password",
            DB::raw('COALESCE(
                vin_user_active.pass_update_date <=
                CURRENT_TIMESTAMP -
                INTERVAL vin_org_active.password_expiration_days DAY, 0
        ) AS password_expired')
        )
        ->join('vin_org_active', "vin_user_active.org", "=", "vin_org_active.id")
        ->where("email", "=", $email)
        ->first();

    return $result;
}

Right now I'm mocking the GetPassword function, but 1. I think the function should be private, not public. 2. The coverage is just %50 because is skipping the whole function.

How would I mock it? right now I have this

$this->db =Mockery::mock('Illuminate\Database\Query\Builder')->makePartial();

    DB::shouldReceive('table')
        ->once()
        ->with("vin_user_active")
        ->andReturn($this->db);

    DB::shouldReceive('raw')
        ->once()
        ->with(Mockery::any())
        ->andReturn(true);

    DB::shouldReceive('select')
        ->once()
        ->with("vin_user_active.id,
            vin_user_active.password,
            DB::raw('COALESCE(
                vin_user_active.pass_update_date <=
                CURRENT_TIMESTAMP -
                INTERVAL vin_org_active.password_expiration_days DAY, 0
        ) AS password_expired'")
        ->andReturn($this->db);

I honestly have no idea what I'm doing, I've never mocked so many levels of function calls.

any idea?


Solution

  • Actually it was simple enough

        DB::shouldReceive("raw")
            ->set('query', 'query test')
            ->andReturn(true);