In order to create a mock version of a global function for unit testing, I define its mock version in the namespace of the SUT class, as is explained here
Consider a case of global function foo()
which is used in namespace Bar
and in namespace Baz
. If I want to use the same mock version of foo()
in both places, it seems I am forced to make two declarations of the mock for foo()
/* bar-namespace-mocks.php */
namespace Bar;
function foo(){
return 'foo mock';
}
/* baz-namespace-mocks.php */
namespace Baz;
function foo(){
return 'foo mock';
}
This code does not conform to the DRY principal. It would be preferred to have one declaration of the foo mock
/* foo-mock.php */
function foo(){
return 'foo mock';
}
and then import into each namespace as needed like the following pseudo code:
/* namespace-mocks.php */
namespace Bar{
import 'foo-mock.php';
}
namespace Baz{
import 'foo-mock.php';
}
Importing using include, e.g.
namespace Baz;
include 'foo-mock.php'
does not cause the mock to be declared in the Baz
namespace. Is there any way to declare a function in more than one namespace without having more than one version of it?