I'm still pretty new with PHPUnit, and I'm trying to figure out how to best test methods as shown in the 3rd class.
I understand how the mock databases work (I think), in that they can return values based on input, from an XML file, etc. I'm not sure how to provide data for the 3rd example, when SQL queries are run inside the methods itself.
I'm trying to test code that accesses info from a DB and performs operations on it. There is no way to feed mocked DB data (e.g., arrays) to these methods currently.
Question: What is the best way to provide data to a method that handles all of its SQL queries internally?
<?php
class ThisMakesSense {
public function checkPassword($original, $hash) {
return (md5($original) == $hash);
}
}
class ThisMakesSenseTest {
public function testCheckPassword() {
$tms = new ThisMakesSense();
$data = array('[email protected]' => 'password1', '[email protected]' => 'password2');
foraech ($data as $email => $password) {
$hash = $this->mockDB()->doStuff()->getPasswordHashByEmail($email);
$this->assertTrue($tms->checkPassword($password, $hash), "Password for {$email} is invalid");
}
$tms->checkPassword($password, $hash);
}
}
/* The '$this->_db' object is basically an OOP way of using the
* mysql_* /mysqli_* functions. Replacing it is not an option
* right now.
*/
class DontUnderstand {
public function checkPassword($email, $password) {
$this->_db->query("SELECT password_hash FROM users WHERE email = '{$email}'");
$row = $this->_db->fetchAssoc();
return (md5($password) == $row['password_hash']);
}
}
class DontUnderstandTest extends PHPUnit_Framework_TestCase {
public function testCheckPassword() {
$du = new DontUnderstand();
$data = array('[email protected]' => 'password1', '[email protected]' => 'password2');
foreach ($data as $email => $pass) {
$this->assertTrue($du->checkPassword($email, $pass), "Password for {$email} is invalid");
}
}
}
(To save someone the trouble of commenting, the md5 and query methods are just for a simple example)