Php 清除静态方法调用

Php 清除静态方法调用,php,phpunit,static-methods,stubbing,Php,Phpunit,Static Methods,Stubbing,所以我在为PHPUnit编写测试时,一个测试开始在各地爆炸。其主要原因是Config::get()为类Core.class.php抛出了-undefined get() 该类在测试中被称为: class CoreTest extends PHPUnit_Framework_TestCase { protected $object; protected function setUp() { $this->object = new Core; }

所以我在为PHPUnit编写测试时,一个测试开始在各地爆炸。其主要原因是Config::get()为类Core.class.php抛出了-undefined get()

该类在测试中被称为:

class CoreTest extends PHPUnit_Framework_TestCase {

    protected $object;

    protected function setUp() {
        $this->object = new Core;
    }

    // .. other tests
}
所以我去调查了这个类,我发现这个结构有以下特点:

public function __construct() {        
    $this->absUrl  = Config::get(Config::ABS_URL);
    $this->baseDir = Config::get(Config::BASE_DIR);
    $this->session = new Session('core');
    return $this;
}
有没有办法把这些删掉?或者以测试不会爆炸的方式处理它们


我在阅读,但我不知道如何在这里应用它。谢谢。

您必须模拟类,而不是执行构造函数,而是构建所需的值,然后在测试中使用模拟

你有试过的样品吗?您可能需要修改Core()类以支持依赖项注入(配置对象和会话对象)

不过,在示例代码中,您可能需要修改Core()类以接受要传递的会话和配置对象(通过构造函数或集合依赖项)以及对会话类的一些修改

class Core
{
    private $SessionObject;
    private $ConfigObject;
    public function __construct(Config $Config, Session $Session)           // Constructor Dependency
    {
        $this->ConfigObject = $Config;
        $this->absUrl  = $this->ConfigObject::get(Config::ABS_URL);
        $this->baseDir = $this->ConfigObject::get(Config::BASE_DIR);
        $this->session = $Session;
        $this->session->SetSessionType('core');
        return $this;
    }
}

现在,生产代码将正确地传递Config和Session对象,然后在测试中使用Mock对象传递具有所需状态的对象,以便在调用对象上的get方法时返回硬设置值

class Core
{
    private $SessionObject;
    private $ConfigObject;
    public function __construct(Config $Config, Session $Session)           // Constructor Dependency
    {
        $this->ConfigObject = $Config;
        $this->absUrl  = $this->ConfigObject::get(Config::ABS_URL);
        $this->baseDir = $this->ConfigObject::get(Config::BASE_DIR);
        $this->session = $Session;
        $this->session->SetSessionType('core');
        return $this;
    }
}
class Core
{
    private $SessionObject;
    private $ConfigObject;
    public function __construct()           
    {
    }

    // Set Dependencies
    public function SetConfigObject(Config $Config)
    {
        $this->ConfigObject = $Config;
    }

    public function SetSessionObject(Session $Session)
    {
        $this->SessionObject = $Session;
    }

    public function BuildObject($SessionType)
    {
        $this->absUrl  = $this->ConfigObject::get(Config::ABS_URL);
        $this->baseDir = $this->ConfigObject::get(Config::BASE_DIR);
        $this->session->SetSessionType($SessionType);
    }
}