6

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

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

        // ... Do something to $foo

        return $foo;
    }
}

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

4

2 回答 2

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']);
}
于 2013-02-26T08:53:07.433 回答
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']);
}
于 2013-02-26T14:09:23.757 回答