Testing the PHP code invoking the static method

I want to test this block of code that should call a static class.

class SomeModule { public function processFoo() { $foo = FooFactory::getFoo(); // ... Do something to $foo return $foo; } } 

I can not change the static class. However, I can change the code inside the module. How can I reorganize this code to one?

+6
source share
2 answers

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

Implemented 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']); } 
+4
source

Passing the name of a static class as a constructor parameter

Implemented Code:

 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; } } 

Test code:

 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']); } 
+1
source

All Articles