views:

513

answers:

2

My quest of starting to use namespaces in PHP keeps continuing. This time PHPUnit gives me problems. My setup() method is like this:

$test = new \MyNamespace\NonPersistentStorage(); // works
$mock = $this->getMock('\\MyNamespace\\NonPersistentStorage'); // doesn't work

The getMock() method only results in PHP looking for a NonPersistentStorage class. Not within the namespace.

Q: What do I need to change to get the getMock() method look for the class in the namespace?

Edit: The double backslash is not the problem. Also see: the manual: (quote)

'Inside a single-quoted string, the backslash escape sequence is much safer to use, but it is still recommended practice to escape backslashes in all strings as a best practice.'

+1  A: 

String references to classes generally don't have the leading backslash. Try removing it and tell us if it works.

EDIT: and if it doesn't, try class_alias to create an alias in the global namespace for that class. However, that would be an ugly solution...

Ignas R
Tried but doesn't work.
koen
Well, by "leading backslash" I meant both leading backslashes, but I hope you understood it anyway.
Ignas R
Oops, sorry. It doesn't work either though.
koen
Try the class_alias workaround then (in case you didn't notice the edit).
Ignas R
Thought this worked: class_alias('\\MyNamespace\\NonPersistentStorage', 'NonPersistentStorage'); $mock = $this->getMock('NonPersistentStorage');but it gives a 'cannot redeclare class' error. Maybe I'm doing it wrong?
koen
It seems that everything is done correctly in your example. But which statement of these two actually throws the error? Is it the class_alias call or the getMock one?
Ignas R
class_alias. Reversing the names gives the same error as before. The problems is I think in the PHPUnit mock code: class PHPUnit_Framework_MockObject_Mock, line 132 of the file is:$isClass = class_exists($className, $callAutoload);This calls my autoload function which doesn't find it. But $className starts as the same string one gives in getMock('className'), but the namespace part is removed. So I guess the solution would be to manually include the file.
koen
Ofcourse requiring doesn't work. Still loads the file in a different namespace.
koen
Well, there should be no problems with autoloading. If a class is already accessible, then it's not autoloaded. Your problem looks strange... Maybe you could try aliasing the class to a completely different name, or removing the getMock call at all and seeing if the aliasing still causes problems.
Ignas R
Also, if you import that class before aliasing, that might be causing the problem. Try removing the "use" statement if it actually exists.
Ignas R
I've solved it with your suggestion of removing the \\ at the start + changing my autoload (added if file_exists before require_once)Thanks for all the suggestions.
koen