php - 排除静态方法调用

标签 php phpunit static-methods stubbing

因此,当测试开始在整个地方爆炸时,我正在为 PHPUnit 编写测试。其主要原因是 Config::get() 正在抛出 - undefined get() for class Core.class.php

此类在测试中被调用,如下所示:

class CoreTest extends PHPUnit_Framework_TestCase {

    protected $object;

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

    // .. other tests
}

所以我去调查了这个类(class),我看到这个构造有以下内容:
public function __construct() {        
    $this->absUrl  = Config::get(Config::ABS_URL);
    $this->baseDir = Config::get(Config::BASE_DIR);
    $this->session = new Session('core');
    return $this;
}

有什么办法可以把这些 stub 吗?还是以测试不会爆炸的方式处理它们?

我正在阅读 This information on stubbing static methods但我不确定如何在这里应用它。谢谢。

最佳答案

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

你有你尝试过的样本吗?您可能需要修改 Core() 类以支持依赖注入(inject)(Config 对象和 Session 对象)。

$stub = $this->getMock('Core');

// Configure the stub.
$stub->expects($this->any())
     ->method('CreateSession')
     ->will($this->returnValue('foo'));

$this->assertEquals('foo', $stub->CreateSession());

但是,在您的示例代码中,您可能需要修改 Core() 类以接受要传递的 Session 和 Config 对象(通过构造函数或通过 Set 依赖项)以及对 Session 类的一些修改。
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);
    }
}

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

关于php - 排除静态方法调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18596675/

相关文章:

php - 在 PHP 中,使用 -> 解引用器调用静态类函数是否有问题

javascript - 通过 javascript 进行 Grocery Crud url 重定向

PHP 和 MySQL -> 显示数据

php - 合并两个数组

php - 使用 PHPUnit 测试 protected 方法的最佳实践(在抽象类上)

PHPUnit代码覆盖生成导致内存耗尽

java - 函数与静态方法

没有 static 的 PHP 函数仍然可以像 static 一样被调用

php - 显示 PHP mysql 表中的图像

php - Laravel 扩展 TestResponse 类