PHPUnit-如何在另一个类的方法中模拟该类? [英] PHPUnit - How to mock the class inside another class's method?

查看:110
本文介绍了PHPUnit-如何在另一个类的方法中模拟该类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在另一个类的方法中模拟该类?

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

例如,

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

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

我可以嘲笑buildRequest吗?

我需要测试此方法getPayload($params),但出现此错误:

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

Class 'Request' not found in...

推荐答案

一个选择是引入一个工厂,该工厂将创建一个Request实例,并将该工厂注入您的类中.您将可以对工厂及其创建的任何事物进行存根.

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.

另一种选择是扩展您正在测试的类,覆盖您的buildRequest()方法以返回模拟并通过此扩展来测试您的类.

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.

最后,PHPUnit为您提供了创建所谓的部分模拟的功能:

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

但是,您的Request类似乎不存在或没有自动加载.您需要先解决此问题.

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

这篇关于PHPUnit-如何在另一个类的方法中模拟该类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆