问题描述
这可能看起来很愚蠢,但我希望不会,但我想创建一个服务,为使用我的项目的人返回模拟对象,以便他们可以模拟我项目中的所有类并测试他们的代码.
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 的测试用例之外创建一个模拟?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!