问题
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