views:

38

answers:

2

In the xdebug code coverage, it shows the line "return false;" (below "!$r") as not covered by my tests. But, the $sql is basically hard-coded. How do I get coverage on that? Do I overwrite "$table" somehow? Or kill the database server for this part of the test?

I guess this is probably telling me I'm not writing my model very well, right? Because I can't test it well. How can I write this better?

Since this one line is not covered, the whole method is not covered and the reports are off.

I'm fairly new to phpunit. Thanks.


public function retrieve_all()
{
    $table = $this->tablename();
    $sql     = "SELECT t.* FROM `{$table}` as t";
    $r         = dbq ( $sql, 'read' );

    if(!$r)
    {
        return false;
    }

    $ret = array ();

    while ( $rs    = mysql_fetch_array ( $r, MYSQL_ASSOC ) )
    {
        $ret[] = $rs;
    }


    return $ret;
}
A: 

I guess the function dbq() performs a database query. Just unplug your database connection and re-run the test.

The reason you have trouble testing is that you are using a global resource: your database connection. You would normally avoid this problem by providing your connection object to the test method (or class).

soulmerge
+1  A: 

In theory, you should be better separating the model and all the database related code.

In exemple, in Zend Framework, the quickstart guide advise you to have :

  • your model classes
  • your data mappers, whose role is to "translate" the model into the database model.
  • your DAOs (or table data gateway) that do the direct access to the tables

This is a really interesting model, you should have a look at it, it enables you to really separate the model from the data, and thus to perform tests only onto the model part (and don't care about any database problem/question)

But in your code, I suggest you to perform a test where you have the dbq() function to return false (maybe having the db connexion to be impossible "on purpose"), in order to have full code coverage.

I often have these kind of situations, where testing all the "error cases" takes you too much time, so I give up having 100% code coverage.

Matthieu