Run
Run

Reputation: 57276

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

Upvotes: 4

Views: 2301

Answers (1)

Jakub Zalas
Jakub Zalas

Reputation: 36231

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.

Upvotes: 5

Related Questions