PHPUnit - How to mock the class inside another class's method?

两盒软妹~` 提交于 2019-12-24 00:44:35

问题


How can I mock the class inside another class's method?

For instance,

protected function buildRequest($params)
{
    return new \Request();
}

public function getPayload($params)
{
    $request = $this->buildRequest($params);
    ....
}

Can I mock buildRequest?

I need to test this method getPayload($params) but I get this error:

Class 'Request' not found in...

回答1:


One option is to introduce a factory that would create a Request instance, and inject the factory into your class. You'd be able to stub the factory and whatever it creates.

Another option is to extend the class you're testing, override your buildRequest() method to return a mock and test your class through this extension.

Finally, PHPUnit offers you the ability to create so called partial mocks:

$request = new \Request();
$params = [1, 2, 3];

$foo = $this->getMock(Foo::class, ['buildRequest']);
$foo->expects($this->any())
    ->method('buildRequest')
    ->with($this->equalTo($params))
    ->willReturn($request);

$payload = $foo->getPayload($params);

However, your Request class doesn't seem to exist or be autoloaded. You'll need to solve this problem first.



来源:https://stackoverflow.com/questions/35334068/phpunit-how-to-mock-the-class-inside-another-classs-method

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