I am trying to get PHPUnit mock objects working on some legacy code that I am working on, but I am having problems connecting it to the object that I am following it, and I am sure that this should be because I am using it incorrectly.
Currently, we have a class that is used exclusively for creating queries, when another class wants to make a request, it creates an object of this class and passes sql and database data to it. I want PHPUnit to replace this object with a mock version that I can verify.
I found that if I create an object layout in a test script, the method being tested just bypasses it. I assume that this is because the method creates and then uses the object locally and not passed as a parameter (in this case, I could just refer to this method with the layout passed as the parameter). The following is an example of what the code looks like:
class SampleClass{ function loadData(){ $sql = "SELECT * FROM users"; $query = new Query(); $query->query($sql); while($row = $query->get_row()){ if($row['email'] = ''){ $this->errors[] = "Email missing from user ".$row['user_id']; } $result[] = $query->get_row(); } $this->users = $result; if(count($user->errors) >= 1){ return $user->errors; }else{ return true; } } } class Query{ function query($sql){ $this->result = mysql_query($sql); } function get_row(){ return mysql_fetch_assoc($this->result); } }
Is there a way to create a mock object in a PHPUnit test file that replaces the $ query object in SampleClass with a mock object that I can use to check the parameters passed and control the response? I cannot replace the request class or change the way it is referenced, since it is widely used in our application, but I would like to at least create some form of test environment for it. Thank any help you can give.
Edited to clarify that there is more than just a query running in the loadData method, which is part of the method I'm trying to test. I hope that the sub is in the double of the get_row query class method, which will return a predefined array of sample data for the method with which it works, and not fall into the actual database
source share