是否可以在PhpUnit的测试用例之外创建模拟? [英] Is it possible to create a mock outside a test case in PhpUnit?

查看:78
本文介绍了是否可以在PhpUnit的测试用例之外创建模拟?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这似乎很愚蠢,但愿如此,但我想创建一个服务,该服务将为使用我的项目的人返回模拟对象,以便他们可以模拟项目中的所有类并测试其代码.

It may seem silly, hope not, but I want to create a service that will return mock objects for people that uses my project so they can mock all the classes from my project and test their code.

我的想法是提供这种服务,以便可以在其他项目的测试用例中调用它,并为每个测试获取适当的模拟.

My idea was to offer this kind of service so it can be called inside other project's test cases and obtain the appropriate mock for each test.

有可能吗?或有其他方法可以做到这一点.顺便说一句,由于项目的限制,我不能使用任何模拟库.

Is that possible? Or there are other ways to do that. Btw, I can't use any mocking library because of project's limitations.

推荐答案

是的,有可能.在getMock方法的内部使用PHPUnit_Framework_MockObject_Generator类.因此,您可以直接使用它:

Yes, it is possible. Under the hood the getMock method uses the PHPUnit_Framework_MockObject_Generator class. So you can use it directly:

PHPUnit_Framework_MockObject_Generator::getMock($originalClassName, $methods)

但是您将失去所有期望的快捷方式,例如$this->once().您将必须自己实例化期望:

But you will lose all the expectation shortcuts like $this->once(). You will have to instantiate the expectations on your own:

$mock->expects(\PHPUnit_Framework_TestCase::once())

查看 PHPUnit源代码看看模拟是如何构建的

Look at the PHPUnit source code to see how the mocks are build

这篇关于是否可以在PhpUnit的测试用例之外创建模拟?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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