测试调用静态方法的PHP代码

时间:2013-02-26 08:53:07

标签: php unit-testing static refactoring phpunit

我想测试这个必须调用静态类的代码块。

class SomeModule {
    public function processFoo() 
    {
        $foo = FooFactory::getFoo();

        // ... Do something to $foo

        return $foo;
    }
}

我无法修改静态类。但是我可以更改模块内的代码。如何重构此代码以进行单元测试?

2 个答案:

答案 0 :(得分:4)

将静态调用移动到单独的方法,然后将其模拟

重构代码:

class SomeModule {
    public function processFoo() 
    {
        $foo = $this->getFoo();

        $foo['hoopla'] = 'doo';

        return $foo;
    }

    protected function getFoo() 
    {
        return FooFactory::getFoo();
    }
}

测试代码:

function testSomeModule() {
    // Whatever we want to simulate FooFactory::getFoo returning
    $foo = array('woo' => 'yay')

    // Create a copy of the class which mocks the method getFoo
    $module = $this->getMockBuilder('SomeModule')
                   ->setMethods(array('getFoo'))
                   ->getMock();

    // Rig the mock method to return our prepared sample
    $module->expects($this->once())
           ->method('getFoo')
           ->will($this->returnValue($foo));

    $result = $module->processFoo();

    $this->assertEquals('yay', $result['woo']);
    $this->assertEquals('doo', $result['hoopla']);
}

答案 1 :(得分:1)

将静态类名称作为构造函数参数

传递

重构代码:

class SomeModule {
    protected $factoryName;

    public function __construct($factoryName = 'FooFactory') {
        $this->factoryName = $factoryName;
    }

    public function processFoo() 
    {
        // PHP Parser limitation requires this
        $factoryName = $this->factoryName;
        $foo = $factoryName::getFoo();

        $foo['hoopla'] = 'doo';

        return $foo;
    }
}

测试代码:

public class MockFactory {
    static public function getFoo() {
        return array('woo' => 'yay');
    }
}

function testSomeModule() {
    $module = new SomeModule('MockFactory');
    $result = $module->processFoo();

    $this->assertEquals('yay', $result['woo']);
    $this->assertEquals('doo', $result['hoopla']);
}