Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHPUnit getMock() with namespace

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.'

edit: What worked for me is in the comments of the answer of Ignace R.

like image 849
koen Avatar asked Aug 11 '09 18:08

koen


2 Answers

use this string instead (without the double backslashes):

$mock = $this->getMock('\MyNamespace\NonPersistentStorage');
like image 112
Philipp Meier Avatar answered Nov 10 '22 05:11

Philipp Meier


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...

like image 2
Ignas R Avatar answered Nov 10 '22 05:11

Ignas R