The project I'm currently working on contains a mix of object-oriented and procedural PHP code. So I have something like this:
function doStuff($value) { $x = $value + 1; return $x; } class MyClass { private $field; public function setMyValue($amount) { $this->field = doStuff($amount) + doStuff(2 * $amount); } }
There are several of these dependencies, but very few (you can count them on one hand). However, I need to write a unit test for a class (using PHPUnit) and I don't know how to mock a function from the terminal (in this case doStuff
). As far as I know, the mocking functionality in PHPUnit only works with classes.
I would have done it without any mocking, but the problem is that some of these functions do some IO operations; I don't think it's a good idea to not mock them in some way.
How can I solve this problem?
The only option I see is dependency injection, since your class wants to use resources outside the class. So this breaks some encapsulation rules.
How I've done this in the past is to put these functions in their own class and require/include them, and when setting the test variables, include a base file with the same semi-"mocked" functions, The file returns to a known state.
My other approach is to create a simple UTILITY class that contains all these data functions and then use dependency injection and mocking to test it.
test:
You can take advantage of PHP's namespace fallback policy when you call functions from a namespace (defined in the global namespace) and always call them unqualified functions.
This allows you to create mocks by providing functions within the caller's namespace.
To make your life extra easy, I packaged it into a library php-mock- phpunit that can be used with PHPUnit: