问题描述
所以,一个函数:
function testMe ($a, $b)
{
$obj = new CalculationObject();
return $obj->calcIt ($a, $b);
}
如何模拟这个创作?
推荐答案
重构该函数以将对象的创建和对象的使用分开.
Refactor the function to separate object creation and object usage.
如果这是类的方法,那么简单的解决方案是将$obj
设置为类属性,以便您可以用模拟代替它.
If this is a method of a class, the trivial solution is to make $obj
a class property so you can replace it with a mock.
如果您始终需要CalculationObject
的新实例,则可以使用工厂模式.
If you always need a new instance of CalculationObject
, the factory pattern can be used.
function testMe ($a, $b)
{
$obj = $this->factory->getNewCalculationObject();
return $obj->calcIt ($a, $b);
}
然后用存根替换$this->factory
,该存根返回您对getNewCalculationObject()
的模拟.
Then replace $this->factory
with a stub that returns your mock for getNewCalculationObject()
.
如果这确实是一个过程函数,而不是方法,则需要将依赖项传递给该函数:
If this is really a procedural function, not a method, you need to pass the dependency to the function:
function testMe ($a, $b, $factory)
{
$obj = $factory->getNewCalculationObject();
return $obj->calcIt ($a, $b);
}
默认情况下,您可以使用普通工厂使其与当前实现向后兼容:
You could use the normal factory by default to make it backwards compatible to your current implementation:
function testMe ($a, $b, $factory = null)
{
if ($factory === null) {
$factory = new CalculationObjectFactory();
}
$obj = $factory->getNewCalculationObject();
return $obj->calcIt ($a, $b);
}
如果您觉得这有点笨拙,请考虑将函数移到类中.
If this looks a bit clumsy to you, consider moving the function into a class.
这篇关于php,如何模拟对象实例化?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!