I've run into a situation with PHPUnit. I have a class that includes a php file that contains non class methods. In my class I have a method that calls the that function. Below is an example of my setup.
class foo
{
public function getInfo()
{
....
$this->GetFunctions();
$data = functionFromRequire();
....
}
public function getFunctions()
{
return require_once '/PATH/TO/FILE/functions.php';
}
}
PHPUnit getMock only mocks class functions. Is there anyway to mock non class functions with PHPUnit? Google results only seem to take me to mocking class functions. Thanks in advance!
In short, PHPUnit did not have functionality to mock namespaces that I could find. I did some refactoring as @markdwhite suggested. I created a new class that included the old file. Then used the magic __call() and call_user_func_array() php functions in the newly created class. Since there was too many namespace functions to manually redo. Hope it helps someone else!
Using namespacing, you can replace your function functionFromRequire
for your getInfo
test. However, requiring the file explicitly as you do in your question will make this difficult.
http://www.schmengler-se.de/en/2011/03/php-mocking-built-in-functions-like-time-in-unit-tests/
You can wrap your test in and class in the same namespace and then replace the functionFromRequire
with your own that will return a set value. As long as you do not specify the namespace of the function, you can replace it and PHP will be able to handle it properly.