Assignments in mock return values
- by zerkms
(I will show examples using php and phpunit but this may be applied to any programming language)
The case: let's say we have a method A::foo that delegates some work to class M and returns the value as-is.
Which of these solutions would you choose:
$mock = $this->getMock('M');
$mock->expects($this->once())
->method('bar')
->will($this->returnValue('baz'));
$obj = new A($mock);
$this->assertEquals('baz', $obj->foo());
or
$mock = $this->getMock('M');
$mock->expects($this->once())
->method('bar')
->will($this->returnValue($result = 'baz'));
$obj = new A($mock);
$this->assertEquals($result, $obj->foo());
or
$result = 'baz';
$mock = $this->getMock('M');
$mock->expects($this->once())
->method('bar')
->will($this->returnValue($result));
$obj = new A($mock);
$this->assertEquals($result, $obj->foo());
Personally I always follow the 2nd solution, but just 10 minutes ago I had a conversation with couple of developers who said that it is "too tricky" and chose 3rd or 1st.
So what would you usually do? And do you have any conventions to follow in such cases?