phpunit避免模拟的构造函数参数 [英] phpunit avoid constructor arguments for mock

查看:86
本文介绍了phpunit避免模拟的构造函数参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何避免phpunit调用模拟对象的构造函数?否则,我需要一个模拟对象作为构造函数参数,另一个用于该对象,以此类推.api看起来像这样:

What is the way to avoid phpunit having to call the constructor for a mock object? Otherwise I would need a mock object as constructor argument, another one for that etc. The api seems to be like this:

getMock($className, $methods = array(), array $arguments = array(),
        $mockClassName = '', $callOriginalConstructor = TRUE,
        $callOriginalClone = TRUE, $callAutoload = TRUE)

我不起作用.即使$callOriginalConstructor设置为false,它仍然会抱怨构造函数参数.

I don't get it to work. It still complains about the constructor argument, even with $callOriginalConstructor set to false.

我在构造函数中只有一个对象,这是一个依赖项注入.因此,我认为那里没有设计问题.

I only have one object in the constructor and it is a dependency injection. So I don't think I have a design problem there.

推荐答案

您可以使用getMockBuilder代替getMock:

$mock = $this->getMockBuilder('class_name')
    ->disableOriginalConstructor()
    ->getMock();

请参见PHPUnit的文档以获取详细信息.

See the section on "Test Doubles" in PHPUnit's documentation for details.

尽管您可以执行此操作,但最好不要这样做.您可以重构代码,因此无需注入具体类(带有构造函数),而只需依赖接口即可.这意味着您可以模拟或存根接口,而不必告诉PHPUnit修改构造函数的行为.

Although you can do this, it's much better to not need to. You can refactor your code so instead of a concrete class (with a constructor) needing to be injected, you only depend upon an interface. This means you can mock or stub the interface without having to tell PHPUnit to modify the constructor behaviour.

这篇关于phpunit避免模拟的构造函数参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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