Created
December 31, 2013 21:03
-
-
Save chartjes/8202226 to your computer and use it in GitHub Desktop.
Example of writing a unit test that has two PDO db calls that need to return two different results
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 | |
// Let's say we have two different result sets | |
$result_set = array(); | |
$result_set[0] = array( | |
array( | |
'id' => 1, | |
'name' => 'Foo', | |
'type' => 'Bar', | |
'status' => 'valid' | |
) | |
); | |
$result_set[1] = array( | |
array( | |
'id' => 2, | |
'name' => 'Fizz', | |
'type' => 'Buzz', | |
'status' => 'valid' | |
), | |
array( | |
'id' => 3, | |
'name' => 'Alpha', | |
'type' => 'Greek', | |
'status' => 'invalid' | |
) | |
); | |
// I always use stdClass as stand-in for PDO objects in my tests | |
$db = $this->getMockBuilder('stdClass')->setMethods(array('fetchAll'))->getMock(); | |
// On the first call to fetchAll() return our first result set | |
$db->expects($this->at(0))->method('fetchAll')->will($this->returnValue($result_set[0])); | |
// On the second call, return the second result set | |
$db->expects($this->at(1))->method('fetchAll')->will($this->returnValue($result_set[1])); | |
// Inject the DB object in as a dependency | |
$widget = new Widget($db); | |
// First DB query happens, return what we expect as the first result set | |
$tmp = $widget->frobagize(); | |
// Second query happens, doing a query that should return the second result set | |
$results = $widget->congeal($tmp); | |
// Do your assertions are whatever you need to do |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment