Search code examples
phpinheritancephpunitlaravel-4mockery

Testing a class that calls parent::function?


I have a model that overloads the where function.

My overloaded method looks like this:

public function where($column, $operator = null, $value = null, $boolean = 'and')
{
    if (in_array($column, $this->metaFields))
    {
        $value    = '%"' . $column . '":"' . $value . '"';
        $column   = 'meta';
        $operator = 'like';
    }

    return parent::where($column, $operator, $value, $boolean);
}

Now using phpunit and mockery I am trying to test this class, I need to test my overloaded where function, all I really care about is what the values are that get passed to parent::where()

My question is, is it possible/how would I mock the parent class so I can do

$metaField = 'colour';
$value     = 'blue';
//on the parent
->shouldReceive('where')->with(['meta', 'like', '%"colour":"blue"%'])->once();

//on the model I am testing
$model->where('colour', 'blue');

Solution

  • all I really care about is what the values are that get passed to parent::where()

    No, you don't. This is an implementation detail you do not need to care about at all with unit testing. Just relax.

    Edit: That was no joke, however if your design requires this, you should favor composition over inheritance so that you can actually mock that "parent" and inject it, therefore test such an expectation. By definition, the parent of a mock in mockery is the class, so the parent in this case is the class with the overloaded method, not it's parent. You can not mock "parents" with mockery (and not with any other PHP mock library I'm aware of).