Assignments in mock return values

Posted by zerkms on Programmers See other posts from Programmers or by zerkms
Published on 2012-06-07T10:36:45Z Indexed on 2012/06/07 10:47 UTC
Read the original article Hit count: 248

(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?

© Programmers or respective owner

Related posts about testing

Related posts about unit-testing