Every repository with this icon (
Every repository with this icon (
Mocking Static Classes
Mocking Static Classes
The $this->mock() method of the Snap_UnitTestCase works for more than just instance level objects. Because PHP lets static objects exist as an instance as well, it is possible to create an object that understands both static and non-static calls. Before getting to far into this page, make sure you understand MockObjects and how they work.
Static objects are mocked exactly the same as an instance object. SnapTest keeps track of how many of the same object you’ve made, and ensures re-mocking the same object results in a fresh static object.
class foo {
public static bar() {}
}
In the above example, we can mock the object just like a normal object. Despite being an all-static class, we still call the construct() method to make the mock object begin to behave normally.
$foo = $this->mock('foo');
Making Calls on a Static Object
You can call a specific method on a mocked static object by using the function SNAP_callStatic($obj, $method, $params).
- $obj the mocked object we got from calling $this→mock()→construct()
- $method the name of the method to call
- $params a list of parameters to pass into $method
The function will determine the class of $obj, and will use the PHP call_user_func_array() method in order to resolve the call properly.
Isolating Static Calls in Non Static Objects
Other times, instead of testing static objects directly, you may want to test an object that calls a static method. For example, a static factory class might be called within a normal instance. The best solution is to refactor that static call into a protected method. It is then possible to use the setReturnValue() method to remove the static call so that it doesn’t happen.
class foo {
public function bar() {
return FooFactory::create('moo');
}
}
and after refactoring:
class foo {
public function bar() {
return $this->fooFactoryCreate('moo');
}
protected function fooFactoryCreate($type) {
return FooFactory::create($type);
}
}







