I need to create a mock object with default set of properties so it can be used elseware in the codebase upon instantiation.
$mock = $this->getMock('MyClass', array(), array(), 'MyClass_Mock');
$mock->prop = 'foobar';
$myclassMock = new get_class($mock);
var_dump($myclassMock->prop); // NULL
// How can I make this dump 'foobar' ?
I’m testing part of the framework that determines, locates, and instantiates these classes so injecting the mocked object would defeat the purpose of the test.
I don’t need to mock any methods.. just dynamically create a mocked class like so:
class MyClass_Mock extends MyClass {
public $prop = 'foobar';
}
Edit: Simplified example
How do you feel about using Reflection?
I’ve not used Reflection a whole lot myself, only for basic introspection. I’m not sure if you’ll be able to fully mimic visibility etc. using it, but I don’t see why not if you continue down the route of writing to a string and
evaling.Edit:
Scanned through the Reflection functions out of curiosity, it is totally possible to fully mimic the class with dummy methods, implementing full visibility constraints, constants, and static elements where appropriate if you dynamically build the class in a string and
evalit.However it looks like it will be a complete mission to really fully support every possibility when it comes down to getting data types correct (you’ll need code to rebuild an array constructor from an array for example)
Best of luck if you go down this route, it requires more brain power than I’m willing to spare right now 🙂
Here’s a little bit of code, you can do the same thing with constants, and create empty methods in a similar way.