Skip to content

Instantly share code, notes, and snippets.

@adamwathan
Last active October 19, 2016 08:26
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save adamwathan/352bba007a8f56a47090 to your computer and use it in GitHub Desktop.
Save adamwathan/352bba007a8f56a47090 to your computer and use it in GitHub Desktop.
Mocks are dangerous
<?php
// Our test
$songs = M::mock('SongCollection');
$songs->shouldReceive('sum')
->with('length')
->andReturn(500);
$album->songs = $songs;
$this->assertEquals(500, $album->getTotalLength());
// This implementation passes
public function getTotalLength()
{
return $this->songs->sum('length');
}
// This implementation fails even though it gives the same result with a real song collection
public function getTotalLength()
{
$result = 0;
foreach ($this->songs as $song) {
$result += $song->length;
}
return $result;
}
// This implementation also fails even though it would give the same result with a real song collection
public function getTotalLength()
{
return $this->songs->reduce(function($total, $song) {
return $total + $song->length;
}, 0);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment