php,如何模拟对象实例化? [英] Php, how to mock object instantiation?

查看:59
本文介绍了php,如何模拟对象实例化?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以,一个函数:

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,如何模拟对象实例化?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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