Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Testing PHP code that calls a static method

I want to test this code block which has to call a static class.

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

        // ... Do something to $foo

        return $foo;
    }
}

I can't modify the static class. I can however change the code inside the module. How can I refactor this code to be unit testable?

like image 251
Eero Heikkinen Avatar asked Feb 26 '13 08:02

Eero Heikkinen


1 Answers

Moving the static call to a separate method which is then mocked

Refactored code:

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

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

        return $foo;
    }

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

Test code:

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']);
}
like image 119
Eero Heikkinen Avatar answered Oct 06 '22 00:10

Eero Heikkinen