Testing a class that calls parent::function?

╄→尐↘猪︶ㄣ 提交于 2019-12-08 14:09:26

问题


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

回答1:


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).



来源:https://stackoverflow.com/questions/17246594/testing-a-class-that-calls-parentfunction

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!