Page 1 of 1

Testing without a real database?

Posted: Mon May 01, 2006 12:42 pm
by Cole22
I have a simple class which which encapsulates access to the MySQL database.

The constructor creates the connection and selects the db using the built in PHP functions. I also have the following two functions:

Code: Select all

public function fetch($sql)
{
$this->query = mysql_query($sql,$this->db);
}

public function getRow()
{
if ($row = mysql_fetch_array($this->query, MYSQL_ASSOC))
   return $row;
else
   return false;
}
My question is, how do I test these two functions without using a real database? i.e. assert that getRow() will return false if $this->query is empty. (The constructor will exit if it cannot make the connection but I want the test to be self-contained and work without a real db).

Ultimately, I want to mock the results returned from the database to test that the data is handled properly.

Are partial mocks the answer? But how do I partially mock the class I am testing?

I'm using SimpleTest BTW.

Thanks in advance!

Posted: Mon May 01, 2006 12:50 pm
by timvw
The easiest would be to use a php version where the mysql extension is not compiled in...
And then make sure *not* to load the mysql extension.. But your mysql_mock_functions...

Posted: Mon May 01, 2006 2:12 pm
by Cole22
Thanks for the reply.

That's okay locally but the problem is on shared hosting I don't have the choice of working with PHP without the MySQL extension compiled in.

I was reading the thread viewtopic.php?t=36426 though (before seeing your reply) and thought maybe I could set up a set of test tables containing test data instead and setting them up in setUp() and tearDown() as in the thread.

Do others test whether their SQL queries are correct and the correct data is being returned?

Posted: Mon May 01, 2006 3:26 pm
by timvw
Imho it all depends on the queries...

In most situations i already know that there will be no problems with my (static) queries so i don't see the point of writing unit tests. In situations where i want to test the 'generated sql' i've always used sample data for the tests..

Posted: Mon May 01, 2006 4:37 pm
by Christopher
I think you are mocking at the wrong level. The data layer is a little too low and its behavior should be predictable. I would recommend mocking the next layer up which is the Data Gateway. I find it is easy to build mocks at that level and create some temporary arrays of data inside them that gets returned by calls to the Gateway. It also allows you to explore what data you actually need before creating database tables.