有没有办法单独测试保存在类变量中的匿名函数?

时间:2014-06-30 11:13:54

标签: php unit-testing phpunit anonymous-function

我的代码类似于:

class FirstClass
{
    public $postProcessor;

    public function __construct()
    {
        $this->postProcessor = function ($x) {return $x;};
    }

    public function get()
    {
        $number = 2 // I want this line to not run when doing unit tests
                    // (It sends an HTTP request in the actual code)
        $this->postProcessor($number);
        // This above line will most likely not work, I had to resort to all
        // sorts of hack to get the function to be actually called.
    }
}

class SecondClass
{
    public function firstMethod()
    {
        $instance = new FirstClass();
        $instance->postProcessor = function ($x) {return $x * 2;};
        return $instance->get();
    }

    public function secondMethod()
    {
        $instance = new FirstClass();
        $instance->postProcessor = function ($x) {return $x / 2;};
        return $instance->get();
    }
}

因此,我希望能够测试这些匿名函数是否正常工作,而无需运行我放置该注释的行。

如果我不能使用匿名函数来执行此操作(或者如果它太不切实际):是否最好将所有这些后处理器定义为类的方法而不是将它们定义为一堆功能?如果是这样,为什么?

0 个答案:

没有答案