Last active
October 19, 2016 08:26
Mocks are dangerous
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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