I must be missing something. I'm trying to stub methods on a class in PHPUnit, but when I invoke the method on the mock object, it tells me that method is undefined.
Example class to stub:
public function mrMethod()
// doing stuff
// specifying all getMock() args to disable calling of class __construct()
$stub = $this->getMock('MyStubClass', array(), array(), 'MockMyStubClass', false, false, false);
//PHP Fatal error: Call to undefined method MockMyStubClass::mrMethod()
$stub = $this->getMock('MyApp\MyStubClass');
// Fatal error: Class 'MyApp\MyApp\MyStubClass' not found
Answering my own question:
After quite a bit of frustration, I did manage to get things working. I'm not sure precisely what the issue was, but did discover a few things that might help others:
Use the fully-qualified namespace minus the first backslash.
Part of my problem was that PHPUnit was creating a stub class
WidgetFactory that was not actually stubbing
MyApp\Widgets\WidgetFactory. One would expect that an exception would occur if trying to stub a non-existent class, but it doesn't seem to happen with the namespace confusion.
Also, there is a question over here that suggests using the class alias method as follows:
class_alias('MyApp\Widgets\WidgetFactory', 'WidgetFactory'); $this->getMock('WidgetFactory');
While this did temporarily solve my problem, I would strongly advise against using it.
class_alias() cannot be called twice for the same alias without raising an exception, which causes obvious problem if used in the
setup() method, or as part of the stub generation.