Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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...
like image 649
Run Avatar asked Oct 22 '25 21:10

Run


1 Answers

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.

like image 95
Jakub Zalas Avatar answered Oct 26 '25 06:10

Jakub Zalas



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!