Reputation: 665
Is there any way to set a class level variable within a mock object?
I have the mock object set similar to this:
$stub = $this->getMock('SokmeClass', array('method'));
$stub->expects($this->once())
->method('method')
->with($this->equalTo($arg1));
Win the real class there is a variable that needs to be set for it to work properly. How can I set that variable within a mock object?
Upvotes: 9
Views: 27781
Reputation: 3569
Here is what works for me:
$stub = $this->getMock('SomeClass');
$stub->myvar = "Value";
Upvotes: 18
Reputation: 61
Don't know why this works but it seems to for me. If you put the __get
magic method as one of the overridden methods e.g.
$mock = $this->getMock('Mail', array('__get'));
You can then you can successfully do
$mock->transport = 'smtp';
Upvotes: 6
Reputation: 316969
The idea of a stub is to replace a dependency with a test double offering the same method interface that (optionally) returns configured return values. This way, the SUT can work with the double like it was the dependency. If you need a specific return value from the stub, you just tell it what it should return, e.g.:
// Create a stub for the SomeClass class.
$stub = $this->getMock('SomeClass');
// Configure the stub.
$stub->expects($this->any())
->method('doSomething')
->will($this->returnArgument(0));
$stub->doSomething('foo'); // returns foo
See http://www.phpunit.de/manual/current/en/test-doubles.html
Upvotes: 3