我想测试这个必须调用静态类的代码块。
class SomeModule {
public function processFoo()
{
$foo = FooFactory::getFoo();
// ... Do something to $foo
return $foo;
}
}
我无法修改静态类。但是我可以更改模块内的代码。如何重构此代码以进行单元测试?
答案 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']);
}